首页 > 解决方案 > 当我尝试从网站获取 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'

标签: pythonjsonurllib

解决方案


不存在元数据

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

推荐阅读