从JSON文件

时间:2017-03-22 16:29:47

标签: python json dictionary keyerror

我试图读取JSON文件(并最终将内容保存到数据库中),但是在运行下面的代码时我收到了KeyError。 See sample JSON供参考。

JSON文件中的所有情况都不存在密钥'durationTimeFrom''durationTimeTo'(仅当eventType80时,我认为)。

如何在尝试读取值之前正确识别缺失的密钥,和/或如何为没有密钥的项目插入虚拟密钥?

我已经搜索了Google / StackOverflow并尝试了if key in dict:dict.get(key)但没有成功。

import json

source = "feed_traffic.json" # JSON file to process
data = json.loads(open(source).read()) # Process JSON

total = data["events"]["totalCount"]
index = 0

events = data["events"]["list"][index:total]

for event in events:

    eid = event["id"]
    type = event['eventType']
    header = event['headingText']
    lat = event['latitude']
    long = event['longitude']
    created = event['created']
    updated = event['updated']
    expires = event['expireTime']
    validFrom = event['durationTimeFrom']
    validTo = event['durationTimeTo']
    status = event['status']

    # Just to check all is well, out data in console
    print("Traffic Event", index, ":", eid, "-", type, "-", header, "(", long, ",", lat, ")")

    index = index+1

1 个答案:

答案 0 :(得分:2)

dict.get。这对我来说可以。你应该改变如下。

# before
validFrom = event['durationTimeFrom']
validTo = event['durationTimeTo']

# after
validFrom = event.get('durationTimeFrom')
validTo = event.get('durationTimeTo')