我用下面的代码得到一个KeyError
。我可以找到的其他解决方案无效。
我正在使用请求进行API调用。它返回以下JSON:
{"status":200,"msg":"OK","result":{"url":"https:\/\/redacted\/something","valid_until":"2019-10-13 12:34:56"}}
我只需要此JSON中的URL,但似乎无法正常工作。
#!/usr/bin/env python
import requests
import json
url = 'https://redacted'
user = 'redacted'
api_token = 'redacted'
r = requests.get(url)
r_dict = r.json()
print(r_dict['url'])
答案 0 :(得分:2)
URL在result
字典中。
print(r_dict['result']['url'])
答案 1 :(得分:0)
我可以使用
解码您的JSON字符串#!/usr/bin/python3
import json
json_in = '{"status":200,"msg":"OK","result":{"url":"https:\/\/example.com\/something","valid_until":"2019-10-13 12:34:56"}}'
json_stuff = json.loads(json_in)
# debugging only print(json_stuff.keys())
print(json_stuff['status'])
print(json_stuff['msg'])
print(json_stuff['result'])
print(json_stuff['result']['url'])
print(json_stuff['result']['valid_until'])