1

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?

2 Answers 2

5

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'}
Sign up to request clarification or add additional context in comments.

4 Comments

Yep but i have this : File "C:\Python33\lib\json\decoder.py", line 352, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: can't use a string pattern on a bytes-like object
Yep, now i have : ValueError: No JSON object could be decoded
@Martialp: Does the exact code I posted in my answer work for you? Try that first. Then move on from there.
With the adresse in your code it's works, not with my adresse, so your solution is ok, the probleme is on my side :)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.