APIs in Action
Encoding and decoding
We use the json module for working with JSON in Python. Let's create a JSON
representation of a Python list by using the following commands:
import json
l = ['a', 'b', 'c']
json.dumps(l)
'["a", "b", "c"]'
We use the json.dumps() function for converting an object to a JSON string.
In this case, we can see that the JSON string appears to be identical to Python's
own representation of a list, but note that this is a string. Confirm this by doing
the following:
s = json.dumps(['a', 'b', 'c'])
type(s)
<class 'str'>
s[0]
'['
Converting JSON to a Python object is also straightforward, as shown here:
s = '["a", "b", "c"]'
l = json.loads(s)
l
['a', 'b', 'c']
l[0]
'a'
We use the json.loads() function, and just pass it a JSON string. As we'll see, this
is very powerful when interacting with web APIs. Typically, we will receive a JSON
string as the body of an HTTP response, which can simply be decoded using
json.loads() to provide immediately usable Python objects.
Using dicts with JSON
JSON natively supports a mapping-type object, which is equivalent to a Python dict.
This means that we can work directly with dicts through JSON.
json.dumps({'A':'Arthur', 'B':'Brian', 'C':'Colonel'})
'{"A": "Arthur", "C": "Colonel", "B": "Brian"}'