如何在python中获取特定于JSON的字段值? [英] How to get a fields particular value of JSON in python?
问题描述
我目前正在从json提取字段,然后加以利用.因此,我有面部参数,并且我想存储每个字段的值.我正在尝试从face的JSON获取Gender值: JSON如下:
I am currently working on extracting fields from json and then make some use of that. Hence I have face parameters, and I want to store each field's value. I am trying to fetch the Gender value from a JSON of face : The JSON is as follows:
{
"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"
}
我想从上面的json中提取女性". 为此,我使用了这个:
I want to extract 'Female' 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 incorrect?
推荐答案
根据您的json示例,gender
在attribute
内部,因此您需要以-
According to your json example , gender
is inside attribute
, so you need to access it as -
gender = soup['face'][0]['attribute']['gender']['value']
另外,似乎values
是回读的(字典)json,所以您可能想使用values
访问它,尽管我不确定您要实现的目标,所以我不能肯定地说
Also, seems like values
is the json that is read back (dictionary), so you may want to access it using values
, though I am not sure what you are trying to achieve so I cannot say for sure.
这篇关于如何在python中获取特定于JSON的字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!