首页 > 解决方案 > 在 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}

标签: pythonjsontypeerrorkeyerror

解决方案


您在问题的第二部分中漂亮打印的 JSON 没有'PrimaryOwner'字段,这就是您收到关键错误的原因。

{'Records': [{'Results': 'YE01'}],
 'TotalRecords': 1,
 'TransmissionResults': '',
 'Version': '5.0.1.1043'}

我认为问题是:为什么您的程序获取的 JSON 数据与您的 Web 浏览器不同?我无法进一步帮助您,但也许其他人可以。


推荐阅读