Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top