liveBook · Manning

Json

As explained in A Pythonic Adventure: From Python basics to a working web app

The Python json module provides functions for encoding Python data structures as JSON and decoding JSON into Python values.

Need to save a coffee-shop order? Python’s json module turns structured data into JSON and can later turn that JSON back into Python values. A module is a file of reusable functions that another program can import. section 8.0

Save an order in three small steps:

  • Import json and create an order dictionary. section 8.0
  • Open orders.json in write mode; Python creates it if it does not exist. section 8.0
  • Call json.dump(order, f), optionally using indent=4 to format the saved JSON. section 8.0
  • Open the file in read mode and call json.load(f) to recover the saved orders. section 8.0

A saved coffee order

Use an order with name, drink, flavor, and topping fields. Add several order dictionaries to an orders list, then pass that list to json.dump(orders, f, indent=4). Later, json.load(f) returns the saved collection. section 8.0

import json
 
order = {
    "name": "Erik",
    "drink": "coffee",
    "flavor": "caramel",
    "topping": "chocolate"
    }
 
f = open("orders.json", "w")
json.dump(order, f)
f.close()

Follow the complete write example: import json, build an order, open orders.json, dump the data, and close the file. section 8.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Demonstrates importing json, dumping dictionaries or lists, formatting output, reading files, and recovering saved values.
Examples
Uses coffee orders, orders.json, multiple order dictionaries, and formatted JSON output.
What it assumes
Assumes basic Python dictionaries, lists, functions, and file opening while teaching modules through shared function files.
What you can do after
Builds a small workflow that writes Python order data to JSON and reads it back.
How it connects
Connects modules with dictionaries, lists, file handling, and reusable functions.

Also explained in

Compare how 4 books explain json →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.