用python解析json [英] json parsing with python
问题描述
我尝试解析这个小json,我想取这个数字:
I try to parse this little json, i want to take the number :
{"nombre":18747}
{"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
重新绑定到网络读取的数据,从而替换模块引用.请勿使用json
作为参考!
You already read the network data; you cannot read it twice. And you are rebinding json
to the network-read data, replacing the module reference. Don't use json
for that reference!
删除print
语句,使用data
作为字符串引用,它将起作用.
Remove the print
statement, use data
for the string reference and it'll work.
工作代码:
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
参数,以确保我们使用正确的编解码器对响应数据进行解码.
where we also make use of any charset
parameter on the response to ensure we use the right codec to decode the response data.
对于上面的http://httpbin.org/get
网址,这将产生:
For the http://httpbin.org/get
url above, this produces:
{'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'}
这篇关于用python解析json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!