Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to work with json?
#1
As I mentioned above, I want to simplify a json string. An example for more details: I have a json string:
{"name":"erik","name_sanitized":"Erik","country":"","gender":"male","samples":31753,"accuracy":96,"duration":"17ms","credits_used":1}
I want to check whether erik is male or female. The Erik's gender is 'male'. Therefore, what I would do to see the final result like that:
Quote:"gender":"male"
Reply
#2
With json library you can load json string and then work with it as with normal dictionary:
import json

json_str = '{"name":"erik","name_sanitized":"Erik","country":"","gender":"male","samples":31753,"accuracy":96,"duration":"17ms","credits_used":1}'
json_loaded = json.loads(json_str)
print(json_loaded['gender'])
Output:
male
Reply
#3
json_str = '{"name":"erik","name_sanitized":"Erik","country":"","gender":"male","samples":31753,"accuracy":96,"duration":"17ms","credits_used":1}'
json_loaded = json.loads(json_str)
var_gender=json_loaded['gender']
if var_gender == "male":
    print("Gender is male")
else:
    print("Gender is not male")
Copy and paste your json string here to understand the structure of json more clearly. http://freeonlinetools24.com/json-decode

array (
'name' => 'erik',
'name_sanitized' => 'Erik',
'country' => '',
'gender' => 'male',
'samples' => 31753,
'accuracy' => 96,
'duration' => '17ms',
'credits_used' => 1,
)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020