liveBook · Manning

JSON

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

JSON is a text-based data-interchange format that represents structured data using objects, arrays, and primitive values.

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

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

How deep it goes
Defines structured data and demonstrates Python file writing, reading, indentation, and multiple-order lists.
Examples
Uses coffee orders containing name, drink, flavor, and topping, saved individually or as a list.
What it assumes
Assumes basic Python dictionaries while introducing modules, lists of dictionaries, and file reading and writing.
What you can do after
Operate Python's json module to write dictionaries or lists to JSON files and load saved data.
How it connects
Connects dictionaries, lists, files, Python modules, and structured versus unstructured data.

Also explained in

Compare how 35 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.