python - 在 Python 中解析 JSON 结果时出现 KeyError
问题描述
我在 Python 中KeyError
解析结果时遇到了一个问题。JSON
我搜索了与 KeyError 相关的其他问题,但到目前为止,没有一个答案有帮助。当我发出网络请求时
https://property.melissadata.net/v4/WEB/LookupProperty?id=MY_LICENSE_KEY&t=&cols=GrpPrimaryOwner&format=json&ff=5933 NE Garfield Avenue, Portland, OR, 97211
从网络浏览器,它返回结果
{"Version":"5.0.1.1043","TransmissionResults":"","TotalRecords":1,"Records":[{"Results":"YS02,YS07,YC01","Parcel":{"FIPSCode":"41051","UnformattedAPN":"R243379","FormattedAPN":"R243379"},"Legal":{},"PropertyAddress":{},"ParsedPropertyAddress":{},"PrimaryOwner":{"Name1Full":"PORTLAND PIEDMONT GUESTHOUSE L","Name1First":"","Name1Middle":"","Name1Last":"PORTLAND PIEDMONT GUESTHOUSE L"
...
Python代码的结果
import requests
import pprint
# api-endpoint
URL = “https://property.melissadata.net/v4/WEB/LookupProperty?id=MY_LICENSE_KEY&t=&cols=GrpPrimaryOwner&format=json”
# location given here
location = "5933 NE Garfield Avenue, Portland, OR 97211"
# defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}
# sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)
# extracting data in json format
data = r.json()
pprint.pprint(data)
name = data['Records'][0]['PrimaryOwner'][0]['Name1Full'][0]
print('name: ' + name)
是
{'Records': [{'Results': 'YE01'}],
'TotalRecords': 1,
'TransmissionResults': '',
'Version': '5.0.1.1043'}
>>> name = data['Records'][0]['PrimaryOwner'][0]['Name1Full'][0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'PrimaryOwner'
>>> print('name: ' + name)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "list") to str
我想PORTLAND PIEDMONT GUESTHOUSE L
从 JSON 结果中提取“”的 Name1Full 值。感谢您提供的任何帮助。
解决方案:
当PARAMS = {'address':location}
替换为PARAMS = {'ff':location}
解决方案
您在问题的第二部分中漂亮打印的 JSON 没有'PrimaryOwner'
字段,这就是您收到关键错误的原因。
{'Records': [{'Results': 'YE01'}],
'TotalRecords': 1,
'TransmissionResults': '',
'Version': '5.0.1.1043'}
我认为问题是:为什么您的程序获取的 JSON 数据与您的 Web 浏览器不同?我无法进一步帮助您,但也许其他人可以。
推荐阅读
- saxon - 直接使用 Saxon API 使用系统函数
- php - 如何更改自定义 WordPress 管理页面的输入字段的值?
- python - 有没有办法用 python sqlite3 迭代地将列输入到数据库中?
- json - Firebase 数据库完整 JSON 列表 - Flutter
- python - Plotly 中的多级树形图
- zsh - 更改 zsh 历史颜色
- azure-virtual-machine - 2 个 Azure VM 之间的服务终结点?
- go - 为什么 Go 生成的 protobuf 文件包含互斥锁?
- android - 应用程序关闭时警报管理器不起作用
- vue.js - Vue 3 模式在重新打开时返回旧数据