2017-08-11 51 views
0

我需要從這個JSON數據訪問文本屬性,所以我可以結束有:如何訪問json數據中的特定文本? [巨蟒]

{'description': {'tags': ['outdoor', 'building', 'street', 'city', 'busy', 'people', 'filled', 'traffic', 'many', 'table', 'car', 'group', 'walking', 'bunch', 'crowded', 'large', 'night', 'light', 'standing', 'man', 'tall', 'umbrella', 'riding', 'sign', 'crowd'], 'captions': [{'text': 'a group of people on a city street filled with traffic at night', 'confidence': 0.8241405091548035}]}, 'requestId': '12fd327f-9b9c-4820-9feb-357a776211d3', 'metadata': {'width': 1826, 'height': 2436, 'format': 'Jpeg'}} 
text = "The Text" 

我是否嘗試過做解析[「標題」] [「文本」],但這沒有工作。請讓我知道你是否可以幫忙謝謝!

回答

0

這裏有兩個問題。首先,captionsdescription下,二,text是名單內的字典的鍵(第一和唯一的項目):

>>> import pprint 
>>> pprint.pprint(parsed) 
{'description': {'captions': [{'confidence': 0.8241405091548035, 
           'text': 'a group of people on a city street filled with traffic at night'}], 
... 

所以,你可以提取text這樣的:

>>> parsed['description']['captions'][0]['text'] 
'a group of people on a city street filled with traffic at night' 

另一個選擇可能是使用簡化遍歷這樣JSON結構第三方庫,例如plucky(全面披露:我是作者)。隨着plucky,你可以說:

>>> from plucky import pluckable 
>>> pluckable(parsed).description.captions.text 
['a group of people on a city street filled with traffic at night'] 

,而不用擔心裏面列出了字典。

0

你可以在這裏使用Python的JSON庫,像下面 -

import json 

your_json_string = "{'description': {'tags': ['outdoor', 'building', 'street', 'city', 'busy', 'people', 'filled', 'traffic', 'many', 'table', 'car', 'group', 'walking', 'bunch', 'crowded', 'large', 'night', 'light', 'standing', 'man', 'tall', 'umbrella', 'riding', 'sign', 'crowd'], 'captions': [{'text': 'a group of people on a city street filled with traffic at night', 'confidence': 0.8241405091548035}]}, 'requestId': '12fd327f-9b9c-4820-9feb-357a776211d3', 'metadata': {'width': 1826, 'height': 2436, 'format': 'Jpeg'}}" 
data_dict = json.loads(your_json_string) 
print(data_dict['description']['captions'][0]['text']) 
+0

這不會因爲字符串'your_json_string'沒有嚴格有效的JSON工作。 –