[英]How to get a fields particular value of JSON in python?
我目前正致力于从json中提取字段,然后使用它。 因此我有面部参数,我想存储每个字段的值。 我试图从面部的JSON中获取Gender值:JSON如下:
{
"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中提取“女性”。 为此,我使用了这个:
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
我的代码在哪里不正确?
根据您的json示例, gender
是内部attribute
,因此您需要访问它 -
gender = soup['face'][0]['attribute']['gender']['value']
此外,似乎values
是回读的json(字典),所以你可能想要使用values
访问它,虽然我不确定你想要实现什么,所以我不能肯定地说。
最后,我得到了答案,这是完美的。
with open('data.json') as da:
data = json.loads(json.load(da))
print data['face'][0]['attribute']['gender']['value']
您可以使用像objectpath这样的库,它使您能够以简单的方式搜索JSON。 只需导入库并构建对象树,然后键入要搜索的单词。
输入:
import json
import objectpath
构建搜索树:
gender_tree = objectpath.Tree(values['face'])
输入你的搜索词
gender_tuple = tuple(actions_tree.execute('$..gender'))
现在,您可以处理gender_tuple
以获取所需的值。
在这里,您要搜索的单词是“ 性别 ”,将其替换为适合您未来搜索的单词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.