[英]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.