1
import urllib2
response = urllib2.urlopen('http://api.xyz.com')
html = response.read()

http://api.xyz.com

{
  "responseHeader":{
    "status":0,
    "QTime":18,
    "params":{
      "indent":"on",
      "q":"",
      "wt":"json",}},
  "response":{"numFound":7984,"start":0,"maxScore":1.0,"docs":[
      {
       "id":"21",
       "first_name":"anurag"
      },
      {
       "id":"31",
       "first_name":"abhishek"
      }
    ]
}

问题是:这个 url 将返回 json 输出。我想读取那个 json 文件,但它显示错误:字符串索引必须是整数,而不是 str。

4

1 回答 1

2

json您需要使用库(包含在 Python 中)将 JSON 响应转换为 python 结构:

import json

import urllib2
response = urllib2.urlopen('http://api.xyz.com')
data = json.load(response)  # note, no `.read()`, the library handles that

print data['response']
于 2013-02-06T18:16:15.447 回答