python - 当我尝试从网站获取 json 元数据时,Python 会引发关键字错误
问题描述
我想迭代并获取 json 元数据的一部分 当我运行下面的代码时,下面的代码会抛出一个 traceback关键字错误: 'metadata' 。我不知道错误是因为函数 printResultS 还是仅仅因为关键字或参数“元数据”
import urllib.request
import json
def printResult(data):
theJSON = json.loads(data)
if "title" in theJSON["metadata"]:
print(theJSON["metadata"]["title"])
count = theJSON ["metadata"]["count"]
print(str(count)+ "events recorded")
def main():
webUrldata = (
"https://www.sciencebase.gov/catalog/item/5d88ea50e4b0c4f70d0ab3c0?format=json")
webUrl = urllib.request.urlopen(webUrldata)
print('Get request:'+ str(webUrl.getcode()))
if (webUrl.getcode() == 200):
data = webUrl.read()
printResult(data)
else:
print("recieved error")
if __name__ == "__main__":
main()
错误
et request:200
Traceback (most recent call last):
File /xample 3.py", line 27, in <module>
main()
File "/xample 3.py", line 22, in main
printResult(data)
File "/xample 3.py", line 7, in printResult
if "title" in theJSON["metadata"]:
KeyError: 'metadata'
解决方案
不存在元数据
theJSON= json.loads(data).get("metadata")
print(theJSON)
给 -
None
&
theJSONkeys = json.loads(data).keys()
print(theJSONkeys)
给
link
relatedItems
id
identifiers
title
summary
body
citation
purpose
provenance
maintenanceUpdateFrequency
hasChildren
parentId
contacts
webLinks
systemTypes
tags
dates
spatial
files
distributionLinks
previewImage
推荐阅读
- arrays - 随机范围是什么意思?
- java - JAVA - 无法从另一个数组正确填充多维数组
- javascript - 生成带有可在角度编辑的输入字段的pdf
- linux - 使用 SoC(ARM、Xilinx)的 Linux 和 RTOS
- javafx - 我在场景构建器中收到此错误:com.gluonhq.charm.glisten.control.Icon
- java - 以 X 时间差运行 2 种方法?
- angular - 我在 Angular 5 项目中的 IE 浏览器上的图标有问题
- java - 使用 ssh 和 ssl 的 java mongodb 连接
- sql - “在这种情况下不允许子查询。只允许标量表达式。”
- javascript - 为什么javascript构造函数打印传递给它的参数?