使用循环时JSON中的键错误

时间:2018-02-11 21:36:43

标签: python json python-3.x

我一直试图从大型JSON字典中提取元素,但在Python 3中使用循环时,经过几次迭代后会出现“关键错误”。

“标签”工作正常,但在尝试提取“值”时,它会给出关键错误。对我做错了什么的想法?

我正在使用的JSON示例:

{ 
"@context" : "nullflood-monitoring/meta/context.jsonld" ,
"meta" : { 
"publisher" : "Environment Agency" ,
"licence" : "http://www.nationalarchives.gov.uk/doc/open-government-
licence/version/3/" ,
"documentation" : "nullflood-monitoring/doc/reference" ,
"version" : "0.9" ,
"comment" : "Status: Beta service" ,
"hasFormat" : [ "nullflood-monitoring/id/measures.csv", "nullflood-
monitoring/id/measures.rdf", "nullflood-monitoring/id/measures.ttl", 
"nullflood-monitoring/id/measures.html" ]
}
,
"items" : [ { 
"@id" : "nullflood-monitoring/id/measuresures/1029TH-level-downstage-i-
15_min-mASD" ,
"datumType" : "nullflood-monitoring/def/core/datumASD" ,
"label" : "RIVER DIKLER AT Bournemouth ON ON THE WATER - level-downstage-i-
15_min-mASD" ,
"latestReading" : { 
  "@id" : "nullflood-monitoring/data/readings/1029TH-level-downstage-i-
15_min-mASD/2018-02-10T12-00-00Z" ,
  "date" : "2018-02-10" ,
  "dateTime" : "2018-02-10T12:00:00Z" ,
  "measure" : "nullflood-monitoring/id/measures/1029TH-level-downstage-i-
15_min-mASD" ,
  "value" : -0.283
}
 ,
"notation" : "1029TH-level-downstage-i-15_min-mASD" ,
"parameter" : "level" ,
"parameterName" : "Water Level" ,
"period" : 900 ,
"qualifier" : "Downstream Stage" ,
"station" : "nullflood-monitoring/id/stations/1029TH" ,
"stationReference" : "1029TH" ,
"unit" : "http://qudt.org/1.1/vocab/unit#Meter" ,
"unitName" : "mASD" ,
"valueType" : "instantaneous"
 }
 , { 
"@id" : "nullflood-monitoring/id/measures/1029TH-level-stage-i-15_min-mASD" 
,
"datumType" : "nullflood-monitoring/def/core/datumASD" ,
"label" : "RIVER DIKLER AT BOURTON ON THE WATER - level-stage-i-15_min-mASD" 
,
"latestReading" : { 
  "@id" : "nullflood-monitoring/data/readings/1029TH-level-stage-i-15_min-
mASD/2018-02-10T12-00-00Z" ,
  "date" : "2018-02-10" ,
  "dateTime" : "2018-02-10T12:00:00Z" ,
  "measure" : "nullflood-monitoring/id/measures/1029TH-level-stage-i-15_min-
mASD" ,
  "value" : 0.245
}

到目前为止我的Python代码:

data = json.loads(source)

for each in data['items']:
    label = (each['label'])
    value = (each['latestReading']['value'])
print(label, value)

我在这里的第一篇文章如果格式不正确,请道歉。

1 个答案:

答案 0 :(得分:0)

您的JSON已损坏,我直接从您提供的链接中获取了JSON one of your comments 使用您的代码运行它完全导致您提到的异常,然后我添加了一个异常处理代码,只是继续迭代JSON:

data = json.loads(source)

for each in data['items']:
    try:
        label = (each['label'])
        value = (each['latestReading']['value'])
        print(label, value)
    except KeyError:
        pass

以下是程序的输出(它太大了,所以我把它发布在pastebin上)

https://pastebin.com/tGfSnZv0

我不确定输出是否理想,但我希望它会以某种方式帮助您解决问题,它肯定比只有6个结果更具描述性。 我的猜测是,英国政府更新的JSON不一致,或者涉及到一些我不知道的语法。