For the final project, we need to be able to encode and decode JSON data.
If you’re not familiar with that format, get a quick introduction at Wikipedia.
In this section, we’ll take a look at what it means to encode and decode JSON data.
Here’s a sample JSON object:
{
"name": "Ada Lovelace",
"country": "England",
"years": [ 1815, 1852 ]
}
In Python, you can make a dict
object that looks just like that:
d = {
"name": "Ada Lovelace",
"country": "England",
"years": [ 1815, 1852 ]
}
But here’s the key difference: all JSON data are strings. The JSON is a string representation of the data in question.
If you have a JSON string, you can turn it into Python native data with the json.loads()
function.
import json
= json.loads('{ "name": "Ada" }')
data
print(data["name"]) # Prints Ada
Likewise, if you have Python data, you can convert it into JSON string format with json.dumps()
:
import json
= { "name": "Ada" }
data
= json.dumps(data)
json_data
print(json_data) # Prints {"name": "Ada"}
If you have a complex object, json.dumps()
will just stick it all together on one line.
This code:
= {
d "name": "Ada Lovelace",
"country": "England",
"years": [ 1815, 1852 ]
}
json.dumps(d)
outputs:
'{"name": "Ada Lovelace", "country": "England", "years": [1815, 1852]}'
You can clean it up a bit by passing the indent
argument to json.dumps()
, giving it an indentation level.
=4) json.dumps(d, indent
outputs:
{
"name": "Ada Lovelace",
"country": "England",
"years": [
1815,
1852
] }
Much cleaner.
JSON requires strings and key names to be in double quotes. Single quotes won’t cut it. Missing quotes definitely won’t cut it.
What’s the difference between a JSON object and a Python dictionary?
Looking at the Wikipedia article, what types of data can be represented in JSON?