How to get the value of a JSON field in python?
I am currently working on extracting fields from json and then using this. Hence I have face parameters and I want to store each field value. I am trying to get Gender value from JSON of face: JSON looks like this:
{
"face": [
{
"attribute": {
"age": {
"range": 5,
"value": 24
},
"gender": {
"confidence": 99.9999,
"value": "Female"
},
"glass": {
"confidence": 99.4157,
"value": "None"
},
"pose": {
"pitch_angle": {
"value": 0.000001
},
"roll_angle": {
"value": 0.650337
},
"yaw_angle": {
"value": -0.42409
}
},
"race": {
"confidence": 98.058,
"value": "Asian"
},
"smiling": {
"value": 3.78394
}
},
"face_id": "42245f24335ad21ea7c54f2db96a09b3",
"position": {
"center": {
"x": 50.121951,
"y": 35.97561
},
"eye_left": {
"x": 43.465122,
"y": 30.670488
},
"eye_right": {
"x": 56.80878,
"y": 30.821951
},
"height": 27.560976,
"mouth_left": {
"x": 45.649512,
"y": 45.041707
},
"mouth_right": {
"x": 55.134878,
"y": 44.858049
},
"nose": {
"x": 50.183415,
"y": 38.410732
},
"width": 27.560976
},
"tag": ""
}
],
"img_height": 410,
"img_id": "1e3007cb3d6cfbaed3a1b4135524ed25",
"img_width": 410,
"session_id": "76ec7f99a471418fa8862a2138cc589d",
"url": "http://www.faceplusplus.com/wp-content/themes/faceplusplus/assets/img/demo/1.jpg?v=2"
}
I want to extract "Girl" from the above json. And for that I used this:
import urllib2
import io, json
from bs4 import BeautifulSoup
data = soup #soup has all the data json
with open('data.json', 'w') as outfile:
json.dump(data, outfile, sort_keys = True, indent = 4, ensure_ascii=False)
#content = json.loads(soup)
jsonFile = open('data.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
gender = soup['face'][0]['gender']['value']
print gender
Where is my code wrong?
source to share
As per your example, the json gender
is inside attribute
, so you need to access it as -
gender = soup['face'][0]['attribute']['gender']['value']
It also seems like values
is the json that is being read (dictionary), so you can access it with values
, although I'm not sure what you are trying to achieve, so I cannot say for sure.
source to share
You can use some libraries such as objectpath , this allows you to easily search for a path in JSON. just import the library and build the object tree, then enter your word you want to find.
Import
import json
import objectpath
Building a search tree:
gender_tree = objectpath.Tree(values['face'])
Typing your search word
gender_tuple = tuple(actions_tree.execute('$..gender'))
Now you can deal with gender_tuple
for your required values.
Here the word you are looking for is gender , replace it with a suitable word for future searches.
source to share