2017-08-11 9 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" 

私が解析された[「キャプション」] [「テキスト」]が、このdidntの仕事をしてみました。ありがとうございました!

答えて

0

2つの問題があります。まず、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' 

もう1つの選択肢として、例えば、plucky(全開示:私は著者です)のようなJSON構造を単純化するサードパーティのライブラリを使用することができます。

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

をし、リスト内の辞書を心配しないで:pluckyでは、あなたが言うことができます。

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ではありませんので、動作しません。 –

関連する問題