2013-02-06 44 views
1
import urllib2 
response = urllib2.urlopen('http://api.xyz.com') 
html = response.read() 

IN http://api.xyz.com獲得URL的內容在python

{ 
    "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。

+1

請包括引發錯誤的代碼,並全面追蹤。 –

回答

2

您需要的JSON響應轉換成蟒蛇結構與json library(包括在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']