2017-02-26 68 views
0

我從中我想提取特定數據的JSON文件。以下是JSON文件:解析一個JSON文件 - Python的

{ 
    "results": [ { 
     "alternatives": [ { 
      "word_confidence": [ 
       [ "Ryan", 0.335 ], 
       [ "how's", 0.589 ], 
       [ "the", 1.0 ], 
       [ "weather", 1.0 ], 
       [ "in", 1.0 ], 
       [ "New", 1.0], 
       [ "York", 0.989 ], 
       [ "today", 0.987 ] 
      ], 
      "confidence": 0.795, 
      "transcript": "Ryan how's the weather in New York today " 
     } ], 
     "final": true 
    } ], 
    "result_index": 0 
} 

使用python,我該如何解析此文件並獲取提取「transcript」?

+0

'進口JSON;數據= json.loads(json_string)' –

+0

@stephen 我用 '進口JSON;數據= json.loads(json_string) ' 返回 '{u'results':[{u'alternatives ':[{u'transcript':U 「瑞恩如何在今天紐約的天氣」,u'confidence' :0.795,u'word_confidence ':[[u'Ryan',0.335],[U 「怎樣的」,0.589],[u'the '1.0],[u'weather',1.0],[u'in' ,1.0],[u'New '1.0],[u'York',0.989],[u'today」,0.987]]}],u'final ':真}],u'result_index':0} ' 現在我必須提取關鍵值「transcript」的數據..如何做到這一點 –

+0

爲此找到的解決方案 data = json.loads(json_data) text_data = data [「results」] [0] [「替代方案 「] [0] [」 成績單「] –

回答

2

要將json字符串轉換爲字典,使用json.loads()。然後拿到成績單,只是引用到dict,如:

代碼:

import json 
data = json.loads(json_string) 
transcript = data['results'][0]['alternatives'][0]['transcript'] 

測試數據:

json_string = """ 
{ 
    "results": [ { 
     "alternatives": [ { 
      "word_confidence": [ 
       [ "Ryan", 0.335 ], 
       [ "how's", 0.589 ], 
       [ "the", 1.0 ], 
       [ "weather", 1.0 ], 
       [ "in", 1.0 ], 
       [ "New", 1.0], 
       [ "York", 0.989 ], 
       [ "today", 0.987 ] 
      ], 
      "confidence": 0.795, 
      "transcript": "Ryan how's the weather in New York today " 
     } ], 
     "final": true 
    } ], 
    "result_index": 0 
} 
"""