Prev | Contents | Next

43 Appendix: JSON

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.

43.1 JSON versus Native

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.

43.2 Converting Back and Forth

If you have a JSON string, you can turn it into Python native data with the json.loads() function.

import json

data = json.loads('{ "name": "Ada" }')

print(data["name"])   # Prints Ada

Likewise, if you have Python data, you can convert it into JSON string format with json.dumps():

import json

data = { "name": "Ada" }

json_data = json.dumps(data)

print(json_data)  # Prints {"name": "Ada"}

43.3 Pretty Printing

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.

json.dumps(d, indent=4)

outputs:

{
    "name": "Ada Lovelace",
    "country": "England",
    "years": [
        1815,
        1852
    ]
}

Much cleaner.

43.4 Double Quotes are Important

JSON requires strings and key names to be in double quotes. Single quotes won’t cut it. Missing quotes definitely won’t cut it.

43.5 Reflect


  1. https://beej.us/guide/bgnet↩︎

  2. https://beej.us/guide/bgnet0/↩︎

  3. https://beej.us/guide/bgnet↩︎

  4. https://beej.us/guide/bgnet0/source/exercises/word/wordserver.py↩︎

  5. https://beej.us/guide/bgnet0/source/exercises/word/wordclient.py↩︎

  6. https://beej.us/guide/bgnet0/source/exercises/tcpcksum/tcp_data.zip↩︎

  7. https://beej.us/guide/bgnet0/source/exercises/tcpcksum/tcp_data.zip↩︎

  8. https://www.youtube.com/watch?v=A1KXPpqlNZ4↩︎

  9. https://beej.us/guide/bgnet0/source/examples/ip-routing-demo.pdf↩︎

  10. https://beej.us/guide/bgnet0/source/exercises/netfuncs/netfuncs.zip↩︎

  11. https://en.wikipedia.org/wiki/Dijkstra’s_algorithm↩︎

  12. https://beej.us/guide/bgnet0/source/exercises/dijkstra/dijkstra.zip↩︎

  13. https://www.wireshark.org/↩︎

  14. https://www.netacad.com/courses/packet-tracer↩︎

  15. https://beej.us/guide/bgnet0/source/exercises/select/select.zip↩︎

  16. https://beej.us/guide/bgnet0/source/exercises/chat/chatui.zip↩︎


Prev | Contents | Next