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