【问题标题】:Python Json - KeyErrorPython Json-KeyError
【发布时间】: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)

标签: python json keyerror


【解决方案1】:

当您在 API 文档中找不到密钥时,您应该只打印 json 的文本,因为它是一种文本格式。

在这里,很明显records 键确实存在,但不是顶级的,而是result 的子键。

你的代码应该是:

for item in json_obj["result"]["records"]:
    print(item['end_of_month'])
    print(item['preliminary'])
    print(item['cards_main'])

【讨论】:

  • 谢谢谢尔盖。这解决了问题。我不知道我必须使用 ["result"]["records"] 而不仅仅是 ["records"]
猜你喜欢
  • 2020-12-27
  • 1970-01-01
  • 2022-08-10
  • 2018-12-15
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
相关资源
最近更新 更多