JSON, or JavaScript Object Notation, is a format for storing structured data and exchanging information between programs. A coffee order fits because it consistently contains a name, drink, flavor, and topping. section 8.0 section 8.1
A small Python program can work with JSON in a few practical steps:
- Import Python's json module. section 8.0
- Create a dictionary representing one order, or a list containing several order dictionaries. section 8.0
- Open orders.json for writing and use json.dump to save the data; indent=4 makes it easier to read. section 8.0
- Close the file, then open it for reading and use json.load to retrieve the saved orders. section 8.0 section 8.1
Save a coffee order
Represent an order with keys such as name, drink, flavor, and topping, then write it to orders.json with json.dump(order, f, indent=4). To save several orders, place dictionaries in a list and dump the list instead. 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()
Shows the complete beginner workflow: import json, open a file, dump an order, and close the file. section 8.0


































