你如何在Python中解析这个JSON?

时间:2016-08-02 02:38:44

标签: python json

下面的JSON

{"result":[
    {
        "spawn_point_id":"89",
        "encounter_id":"1421",
        "expiration_timestamp_ms":"1470105387836",
        "latitude":38.22,
        "longitude": -91.27
    },
    {
        "distance_in_meters":10,
        "encounter_id":"9677"
    },
    {
        "distance_in_meters":10,
        "encounter_id":"1421"
    },
    {
        "spawn_point_id":"11",
        "encounter_id":"2142",
        "expiration_timestamp_ms":"1470105387444",
        "latitude":38.00,
        "longitude": -91.00
    }
]}

我希望输出看起来像

spawn 89 at lat 38.22 long -91.27
spawn 11 at lat 38.00 long -91.00

我使用json.loads,它实际上让json看起来很时髦。

目前为止的代码:

c = json.loads(r.content)
for d in c['result']:
    if d['latitude'] is not None:
        print(str(d['latitude']))

似乎有点工作,但后来得到错误

Traceback (most recent call last):
File "fast0.py", line 11, in <module>
if d['latitude'] is not None:
KeyError: 'latitude'

1 个答案:

答案 0 :(得分:0)

您正在寻找一个不存在的密钥。尝试:

c = json.loads(r.content)
for d in c['result']:
    if 'latitude' in d:
        print(str(d['latitude']))