2013-12-11 19 views
1

解析我试图解析这个小JSON,我想借此数量:JSON与Python

{"nombre":18747}

我尝试:

import urllib.request 
request = urllib.request.Request("http://myurl.com") 
response = urllib.request.urlopen(request) 
print (response.read().decode('utf-8')) //print -> {"nombre":18747} 

import json 
json = (response.read().decode('utf-8')) 
json.loads(json) 

但我有:

Traceback (most recent call last): 
    File "<pyshell#38>", line 1, in <module> 
    json.loads('json') 
AttributeError: 'str' object has no attribute 'loads' 

任何帮助?

回答

5

已经读取网络数据;你不能读它两次。并且您正在重写json到网络读取数据,替换模块引用。请勿使用json作为参考!

删除print声明,使用data作为字符串引用,它将起作用。

工作代码:

import urllib.request 
import json 

request = urllib.request.Request("http://httpbin.org/get") 
response = urllib.request.urlopen(request) 
encoding = response.info().get_content_charset('utf8') 
data = json.loads(response.read().decode(encoding)) 

,我们还利用在响应任何charset参数,以确保我们使用正确的编解码器的反应数据进行解码。

对于上述http://httpbin.org/get的URL,这将产生:

{'args': {}, 'headers': {'Host': 'httpbin.org', 'Accept-Encoding': 'identity', 'Connection': 'close', 'User-Agent': 'Python-urllib/3.3'}, 'origin': '12.34.56.78', 'url': 'http://httpbin.org/get'} 
+0

是的,但我有这样的:文件“C:\ Python33 \ lib \ json \ decoder.py”,行352,解码 obj,结束= self.raw_decode(s,idx = _w(s,0)。 ()) TypeError:不能在类似字节的对象上使用字符串模式 – mpgn

+0

@Martialp:啊,我明白了;这改变了Python 3.我会更新。 –

+0

是的,现在我有:ValueError:没有JSON对象可以被解码 – mpgn

1

名的字符串不同,例如改为:

json = (response.read().decode('utf-8')) 
json.loads(json) 

写:

input = (response.read().decode('utf-8')) 
json.loads(input) 

随着事情是这样的目前在你的问题中,你正在用那个变量名覆盖导入的json模块是字符串。同时删除打印语句。