bli*_*ndy 5 python json dictionary urllib2 python-2.7
我是python(和一般编码)的新手,我已经走到这一步但我遇到了麻烦.我正在查询一个返回json文件的Web服务,该文件包含每个员工的信息.我想为每位员工提供几个属性,但我遇到了一些麻烦.
到目前为止我有这个脚本:
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']
Run Code Online (Sandbox Code Playgroud)
它返回的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",
},
Run Code Online (Sandbox Code Playgroud)
您可以看到,通过脚本,我可以返回索引1中员工的姓名.但我希望有更多的内容:print j[**0 through len(j)**]['name']
因此它将打印出每个员工的姓名(最好是电话号码) json列表.
我很确定我接近错了,但我需要一些反馈和指导.
您的JSON是list
的dict
对象.通过这样做j[1]
,您将访问索引列表中的项目1
.为了获取所有记录,您需要迭代列表的所有元素:
for item in j:
print item['name']
Run Code Online (Sandbox Code Playgroud)
在你的答案中提到的j
结果在哪里j = json.loads(the_page)