json parsing with python

。_饼干妹妹 提交于 2020-01-25 00:45:31

问题


I try to parse this little json, i want to take the number :

{"nombre":18747}

I try :

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)

But I have:

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

Any help?


回答1:


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!

Remove the print statement, use data for the string reference and it'll work.

Working code:

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))

where we also make use of any charset parameter on the response to ensure we use the right codec to decode the response data.

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'}



回答2:


name your string differently, for example instead :

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

write :

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

With the way it is currently in your question, you are overriding imported json module with that variable name which is string. Also remove the print statement.



来源:https://stackoverflow.com/questions/20525513/json-parsing-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!