Skip to content Skip to sidebar Skip to footer

Json Parsing With Python

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

Solution 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
importjsonrequest= 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'}

Solution 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.

Post a Comment for "Json Parsing With Python"