处理以下JSON文件时出现错误

时间:2019-06-04 22:22:35

标签: json python-3.x

我从网络上获取了一个提要,但我需要对其进行处理,但是却遇到了一个错误,并且不确定如何处理列表中的列表。我敢肯定,这是我所忽略的简单事情。

JSON文件就是这样

     {"alerts":[{"country":"AS","nThumbsUp":0,"city":"Albion, Vic","reportRating":3,"confidence":0,"reliability":5,"type":"JAM","uuid":"19c56810-3b8b-31a1-a658-c779f99b9388","magvar":279,"subtype":"JAM_STAND_STILL_TRAFFIC","street":"Polish Club Driveway","location":{"x":144.807815,"y":-37.771797},"pubMillis":1559688120073},{"country":"AS","nThumbsUp":0,"city":"Calder Park","reportRating":2,"confidence":0,"reliability":5,"type":"WEATHERHAZARD","uuid":"283a1bb4-6c0e-3f84-a4ff-cf187aa97dbd","roadType":2,"magvar":221,"subtype":"HAZARD_ON_SHOULDER_CAR_STOPPED","street":"Calder Park Dr","location":{"x":144.761619,"y":-37.679113},"pubMillis":1559689265092},

url = urllib.request.urlopen(turl)
output = url.read().decode('utf-8')
raw_api_dict = json.loads(output)

for x in json.loads(output)['alerts']:
    print(x['country'])
    print(x['nThumbsUp'])
    print(x['reportRating'])
    print(x['confidence'])
    print(x['reliability'])
    print(x['type'])
    print(x['uuid'])
    print(x['roadType'])
    print(x['magvar'])
    print(x['subtype'])
    print(x['street'])
    print(x['location_x'])
    print(x['location_y'])
    print(x['pubMillis'])

***这是错误**     追溯(最近一次通话):     在第58行的文件“ waze.py”中     打印(x ['location_x'] [0])     KeyError:“ location_x”

2 个答案:

答案 0 :(得分:0)

主要是因为您使用的JSON无效。使用以下JSON。

{
"country": "AS",
"nThumbsUp": 0,
"city": "Taylors Hill",
"reportRating": 1,
"confidence": 0,
"reliability": 5,
"type": "JAM",
"uuid": "a0241505-b0f8-3e83-a9c9-678f3c9039c5",
"roadType": 2,
"magvar": 103,
"subtype": "JAM_STAND_STILL_TRAFFIC",
"street": "Taylors Rd",
"location_x": 144.764866,
"location_y": -37.725576,
"pubMillis": 1559626611999 }

Python编译器将'视为特殊字符。

  

在代码中运行之前,始终使用JSON Validator来验证JSON。希望我的回答对您有所帮助。请参阅上面的评论。我猜在这种情况下json.dumps()可以为您提供帮助。

答案 1 :(得分:0)

import json

person_dict = {'name': 'Bob',
'age': 12,
'children': None
}
person_json = json.dumps(person_dict)

# Output: {"name": "Bob", "age": 12, "children": null}
print(person_json)

person_dict = json.loads(person_json)

print( person_dict)

print(person_dict['age'])

使用json.dumps解决此问题(如果可行)。