用python解析json [英] json parsing with python

查看:136
本文介绍了用python解析json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试解析这个小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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆