2017-07-31 27 views
1

私は、APIからデータを解析するプログラムを作成しました。 apiはJSON形式のデータを返します。私はそれを解析しようとすると、それはPythonでJSONを解析する際にKeyerrorを取得する

url = json.loads(r.text)["url"] 
    KeyError: 'url' 

私にキーエラーになります。これは、コード

url = json.loads(r.text)["url"] 

の一部である私は、プレーンフィールドのデータを取得しようとしています。ここではAPIからの出力は次のとおりです。

{"updates":[{"id":"a6aa-8bd","description":"Bug fixes and enhancemets","version":"8.1.30","type":"firmware","url":"https://con-man.company.com/api/v1/file-732e844b","updated":"2017-07-25"}]} 
+1

そのオブジェクトの唯一のキーが「更新」であることは理解できますか? –

答えて

0

、これを試して、それが更新(リスト)の内側にあるので、あなたはそれゆえあなたは、インデックス、その後keyを渡す必要があり、urlにアクセスすることはできません。

ワンライナー:

>>> url = json.loads(r.text)['updates'][0]['url'] 
'https://con-man.company.com/api/v1/file-732e844b' 

明示

>>> jobj = json.loads(r.text) 
>>> url = jobj['updates'][0]['url'] 
'https://con-man.company.com/api/v1/file-732e844b' 
+0

ダウン投票ありがとう!説明してください? –

0

url = json.loads(r.text)["updates"][0]["url"] 
+0

'updates'キーには、辞書のリストに値があります。 'updates'のインデックスを渡し、' url'キーにアクセスする必要があります。 –

0
{ 
"updates": [ 
       { 
       "id":"a6aa-8bd", 
       "description":"Bug fixes and enhancemets", 
       "version":"8.1.30", 
       "type":"firmware", 
       "url":"https://con-man.company.com/api/v1/file-732e844b", 
       "updated":"2017-07-25" 
       } 
      ] 
} 

、それは別のリストを持っており、そのリストの中に、あなたは別のdict

があり、そのキー値の「更新」キーを1つだけ持って、あなたのdictの視覚化するようにしてくださいあなたの場合はそうです

_dict = json.loads(r.text) # read file and load dict 
_list = _dict['updates']  # read list inside dict 
_dict_1 = _list[0]  # read list first value and load dict 
url = _dict_1['url']  # read 'url' key from dict 
関連する問題