NetAuto Academy

Networking Data & Formats

Working with JSON in Python

Beginner12 min read

What you'll learn

  • What JSON actually is, and why it looks so close to Python already
  • The four json module functions: loads, load, dumps, and dump
  • How to turn a JSON string into a Python dictionary, and back
  • How to read a JSON file into a list of device dictionaries
  • The true/false/null vs True/False/None gotcha, and why it doesn't actually cause problems in practice
🎓 Teach This Lesson

Listen to a guided explanation of this lesson.

Spoken narration isn't supported in this browser.

JSON is almost exactly a Python dict already

"Working with Files & Structured Data," back in the Python module, showed you what JSON looks like as plain text:

device.json
{
  "hostname": "SW1",
  "ip": "10.10.10.1",
  "platform": "cisco_ios"
}

This should look almost identical to a Python dictionary — because it is one, just written down as text instead of living in memory.

That resemblance isn't an accident — JSON (JavaScript Object Notation) was designed to map cleanly onto exactly this kind of structured data. This lesson is about the standard library's json module, which handles the conversion between "text on disk" and "a real Python dictionary you can use" in both directions.

Four functions, one naming pattern

the four functions
import json

json.loads(text)        # string  -> Python
json.load(file_object)  # file    -> Python
json.dumps(data)        # Python  -> string
json.dump(data, file_object)  # Python -> file

The 's' stands for 'string.' loads/dumps work on a string already in memory; load/dump work directly on an open file. Everything else about the four is the same idea, just in opposite directions.

Reading JSON

parse_device.py
import json

device_json = '{"hostname": "SW1", "ip": "10.10.10.1", "platform": "cisco_ios"}'

device = json.loads(device_json)

print(device["hostname"])   # SW1
print(type(device))         # <class 'dict'>

json.loads() takes a JSON string and returns a real Python dictionary — device['hostname'] works exactly like every dictionary you've used since Lesson 3 of the Python module, because that's exactly what it is now.

Quick checkConcept check
After running 'device = json.loads(device_json)', what kind of Python object is device?

Reading a JSON file

More often, JSON lives in a file, not a string already sitting in your code — that's what json.load() (no 's') is for:

load_inventory.py
import json

with open("inventory.json") as f:
  devices = json.load(f)

for device in devices:
  print(device["hostname"], device["ip"])

open() gives you a file object, exactly like Lesson 6's file-reading examples. json.load(f) reads the whole file and parses it in one step — if inventory.json holds a JSON list of device objects, devices comes back as a Python list of dictionaries, ready for the same kind of loop you've used all module.

Quick checkIdentify the correct code
Which line correctly reads and parses an already-open JSON file object named f into Python data?

Writing JSON

Going the other direction — Python data to a JSON file — uses dump():

save_inventory.py
import json

devices = [
  {"hostname": "SW1", "ip": "10.10.10.1", "platform": "cisco_ios"},
  {"hostname": "SW2", "ip": "10.10.10.2", "platform": "cisco_ios"},
]

with open("inventory.json", "w") as f:
  json.dump(devices, f, indent=4)

json.dump(devices, f, indent=4) writes devices out as JSON text into the open file f. indent=4 isn't required — without it, the file would still be valid JSON, just all on one line — but it makes the saved file readable by a person too, not only by a script.

Quick checkScenario
A script has a Python list of device dictionaries in memory and needs to save it as a JSON file. Which function does that?

The true/false/null gotcha

Raw JSON text uses true, false, and null — lowercase, and slightly different words than Python's True, False, and None. This looks like it should be a problem, and in practice, isn't one:

json_booleans.py
import json

data = json.loads('{"reachable": true, "last_error": null}')

print(data["reachable"])    # True  (a real Python bool)
print(data["last_error"])   # None  (a real Python None)

json.loads() automatically converts JSON's true/false/null into Python's True/False/None as part of parsing — you never have to do that conversion yourself. It's worth knowing the raw text looks different, so a .json file you open in a text editor doesn't look 'wrong.'

Where you'll actually see this

Plenty of real network tooling speaks JSON directly — many platforms support a | json or similar output modifier on show commands, and REST APIs on network controllers return JSON as their default format. Everything in this lesson is directly what you'd use to work with that output.

Quick checkMyth check
JSON text uses lowercase true/false/null while Python uses True/False/None. Does this difference cause problems when using the json module?

Key takeaways

  • JSON maps almost directly onto Python dicts and lists — the json module handles the conversion in both directions.
  • loads() and dumps() (with an 's') work on strings already in memory; load() and dump() work directly on open files.
  • json.load(f) is the most common pattern for reading a device inventory saved as a .json file.
  • json.dump(data, f, indent=4) writes Python data out as readable JSON — indent=4 is optional but makes the file human-readable too.
  • JSON's true/false/null and Python's True/False/None are automatically converted for you — the difference in spelling never needs manual handling.