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?
https://beej.us/guide/bgnet↩︎
https://beej.us/guide/bgnet0/↩︎
https://beej.us/guide/bgnet↩︎
https://beej.us/guide/bgnet0/source/exercises/word/wordserver.py↩︎
https://beej.us/guide/bgnet0/source/exercises/word/wordclient.py↩︎
https://beej.us/guide/bgnet0/source/exercises/tcpcksum/tcp_data.zip↩︎
https://beej.us/guide/bgnet0/source/exercises/tcpcksum/tcp_data.zip↩︎
https://www.youtube.com/watch?v=A1KXPpqlNZ4↩︎
https://beej.us/guide/bgnet0/source/examples/ip-routing-demo.pdf↩︎
https://beej.us/guide/bgnet0/source/exercises/netfuncs/netfuncs.zip↩︎
https://en.wikipedia.org/wiki/Dijkstra’s_algorithm↩︎
https://beej.us/guide/bgnet0/source/exercises/dijkstra/dijkstra.zip↩︎
https://www.wireshark.org/↩︎
https://www.netacad.com/courses/packet-tracer↩︎
https://beej.us/guide/bgnet0/source/exercises/select/select.zip↩︎
https://beej.us/guide/bgnet0/source/exercises/chat/chatui.zip↩︎