【发布时间】:2017-02-27 22:32:16
【问题描述】:
我正在尝试从 API 检索记录,并最终希望将它们存储在数据框中,以便进行一些分析。但我收到以下错误:
for item in json_obj["records"]:
KeyError: 'records'
代码:
import urllib.request
import json
import urllib.request
url = 'https://eservices.mas.gov.sg/api/action/datastore/search.json?resource_id=7f1363cc-3875-4e03-a389-fc47342bb840&limit=5'
response = urllib.request.urlopen(url).read().decode('UTF-8')
json_obj = json.loads(response)
for item in json_obj["records"]:
print(item[end_of_month'])
print(item['preliminary'])
print(item['cards_main'])
【问题讨论】:
-
好的,所以
json_obj字典中没有'records'键。除此之外,您认为任何人都可以告诉您什么?你知道它有有什么键吗?你试过打印出来吗?还有其他debugging吗? -
正如 jonrsharpe 所说,看看实际上有哪些键:
console.log(Object.keys(json_obj))应该很容易看到。 -
偷看数据,你要
json_obj["result"]["records"] -
@RichardDunn 正确的想法,错误的语言!
-
@jonrsharpe 哦,亲爱的。这就是我整天工作然后熬夜的原因。
print(json_obj.keys())在那种情况下......或者更好的是,我用来在 python 中探索数据的东西:from pprint import pprint然后只是pprint(json_obj)