在python中获取JSON信息

时间:2014-10-03 05:26:12

标签: python json

数据库样本:

"metros" : [
        {
            "code" : "SCL" ,
            "name" : "Santiago" ,
            "country" : "CL" ,
            "continent" : "South America" ,
            "timezone" : -4 ,
            "coordinates" : {"S" : 33, "W" : 71} ,
            "population" : 6000000 ,
            "region" : 1
        } , {
            "code" : "LIM" ,
            "name" : "Lima" ,
            "country" : "PE" ,
            "continent" : "South America" ,
            "timezone" : -5 ,
            "coordinates" : {"S" : 12, "W" : 77} ,
            "population" : 9050000 ,
            "region" : 1
        } 

我正在尝试打印所有城市名称。我的代码是:

Jdata = json.loads(self.data)
for i in Jdata["metros"]:
    print Jdata["name"]

但是当我跑这个时,我得到了“KeyError:'name'”

获取城市名称的正确语法是什么?

2 个答案:

答案 0 :(得分:4)

尝试:

for city in Jdata['metros']:
    print city['name']

当你使用Jdata['name']时,它会尝试在地铁中寻找钥匙,这显然不存在。

答案 1 :(得分:1)

{"metros":[{"code":"SCL","name":"Santiago","Region":"1"},{"code":"LIM","name":"Lima","Region":"1"}],
}

然后你可以使用你的代码:

import json
from pprint import pprint
json_data=open('json_data')

data = json.load(json_data)
pprint(data)
json_data.close()
With data, you can now also find values in like so:

data["metros"][1]["name"]