Go From Bytes to Dictionary
json module can handle decoding JSON data even without encoding information. You may recall working with JSON in the first lesson where you performed basic HTTP requests, and you didn’t need to bother with encoding then. What you’ll find now is that you may not need
.get_content_charset() when you work with JSON content.
02:07 It also specifies how JSON should be used as a media type in HTTP headers and other internet-related contexts. That’s not to say that every single server plays by the rules, but generally you can assume that if JSON is being transmitted, it’ll almost always be encoded using UTF-8.
Now let’s go ahead and use
urlopen() like we have before. So
with urlopen() and pass in
response, and you will set the
body variable to
and while you’re at it, go ahead and print out the
data. Let’s head over to the terminal to see what this looks like. So we have
py urllib_requests.py As you can see, the first
print() printed out
'bytes' like we expected, and the second
print() printed out dictionary.
As you can see, the
json module handles the decoding automatically and produces a Python dictionary. Almost all APIs return key-value information as JSON, although you might run into some older APIs that work with XML.
Become a Member to join the conversation.