如何在python中获取JSON的字段特定值?
我目前正在从json中提取字段,然后利用这些字段。因此我有面参数,我想存储每个字段的值。我试图从脸的JSON中获取性别值: JSON如下所示:如何在python中获取JSON的字段特定值?,python,json,Python,Json,我目前正在从json中提取字段,然后利用这些字段。因此我有面参数,我想存储每个字段的值。我试图从脸的JSON中获取性别值: JSON如下所示: { "face": [ { "attribute": { "age": { "range": 5, "value": 24 }, "gender": { "confidence": 99.9999, "v
{
"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中提取'Female'。
为此,我用了这个:
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']
您可以使用一些库,如,它使您能够以简单的方式在JSON中搜索。 只需导入库并构建对象树,然后键入要搜索的单词 导入:
import json
import objectpath
gender_tree = objectpath.Tree(values['face'])
构建搜索树:
import json
import objectpath
gender_tree = objectpath.Tree(values['face'])
键入搜索词
gender_tuple = tuple(actions_tree.execute('$..gender'))
现在,您可以处理所需值的gender\u tuple
在这里,您正在搜索的单词是“性别”,请将其替换为适合以后搜索的单词。此代码导致了什么错误或问题?意思是它给出了一个语法错误,或者什么也不打印,等等……作为补充,如果你的json可能比这更复杂,那么拥有一个查询支持可以让你的生活更轻松:我下载了这个包。但是我不知道如何纠正我得到的错误。这就是错误!我试着将json保存在一个变量和一个文件中……我也试过了,它给出了一个错误,那就是TypeError:字符串索引必须是整数,也可能在访问这个之前打印出soup的值,并更新这个回溯(最近一次调用):文件“ml.py”,第15行,在gender=str(soup['face'][0]['attribute']['gender']['value'])TypeError:字符串索引必须是整数这是完整的回溯。soup与jsonI完全相同。jsonI也尝试用值替换soup。两者都给出相同的错误。soup的打印结果如何?