我是python的新手(和一般的编码),我已经学到了这一步,但是遇到了麻烦。我正在查询一个Web服务,该服务返回一个json文件,其中包含每位员工的信息。我想为每个员工仅介绍几个属性,但是遇到了一些麻烦。

到目前为止,我有这个脚本:

import json
import urllib2

req = urllib2.Request('http://server.company.com/api')
response = urllib2.urlopen(req)
the_page = response.read()

j = json.loads(the_page)

print j[1]['name']

它返回的JSON看起来像这样...
{
    "name": bill jones,
    "address": "123 something st",
    "city": "somewhere",
    "state": "somestate",
    "zip": "12345",
    "phone_number": "800-555-1234",
},
{
    "name": jane doe,
    "address": "456 another ave",
    "city": "metropolis",
    "state": "ny",
    "zip": "10001",
    "phone_number": "555-555-5554",
},

您可以看到,通过该脚本,我可以在索引1中返回员工的姓名。但是,我希望在以下内容中添加更多内容:print j[**0 through len(j)**]['name'],以便它将打印出每个员工的姓名(最好还有电话号码)在json列表中。

我相当确定我正在处理错误的内容,但是我需要一些反馈和指导。

最佳答案

您的JSON是list对象的dict。通过执行j[1],您将在索引1处访问列表中的项目。为了获取所有记录,您需要将列表的所有元素迭代为:

for item in j:
    print item['name']

答案中提到的jj = json.loads(the_page)的结果

关于python - 如何从JSON中提取重复 key ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39605640/

10-11 22:03
查看更多