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



