json用python解析

mpg*_*pgn 1 python json urllib python-3.x

我试着解析这个小json,我想拿这个数字:

{ "农布雷":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)
Run Code Online (Sandbox Code Playgroud)

但是我有:

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

有帮助吗?

Mar*_*ers 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))
Run Code Online (Sandbox Code Playgroud)

我们还在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'}
Run Code Online (Sandbox Code Playgroud)