我尝试解析这个小 json,我想获取数字:
{"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'
有什么帮助吗?
请您参考如下方法:
您已经阅读了网络数据;你不能读它两次。您正在将 json 重新绑定(bind)到网络读取数据,替换模块引用。不要使用 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'}
