liveBook · Manning

JSON

As explained in Python Workout: 50 ten-minute exercises

A JSON file is a text file whose contents are serialized according to the JSON format.

When a program needs to exchange data or preserve Python structures on disk, JSON provides a text representation that other languages can read. Web services and APIs commonly send and receive it. section 5.26 section 5.0

JSON is a data representation rather than a Python data type. Python's json module converts JSON text into built-in objects such as lists and dicts, and converts Python data back into JSON-formatted strings. Use json.load for a file object, json.loads for a string, and the corresponding dump functions when writing. section 5.27 section 5.36

A practical JSON-processing workflow is:

  • Find relevant files, for example with glob.glob('scores/*.json'). section 5.27
  • Open each file and call json.load to obtain Python data structures. section 5.26
  • Transform the resulting lists and dicts, then calculate or organize the required results. section 5.27
  • Write transformed data with json.dump when a JSON file is the desired output. section 5.36

Summarizing class scores

Given files such as scores/9a.json and scores/9b.json, read each JSON array of subject-score dictionaries, collect scores by subject, and print each class's minimum, maximum, and average. JSON requires double quotes, not Python's single quotes. section 5.26

[{"math" : 90, "literature" : 98, "science" : 97},
{"math" : 65, "literature" : 79, "science" : 85},
{"math" : 78, "literature" : 83, "science" : 75},
{"math" : 92, "literature" : 78, "science" : 85},
{"math" : 100, "literature" : 80, "science" : 90}
]

Inspect a complete JSON array of dictionaries representing student scores. section 5.26

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains parsing, serialization, file loading, and directory-wide processing, while stopping short of JSON grammar internals.
Examples
Works through class-score arrays, directory-wide statistics, filesystem metadata, and CSV-style passwd conversion.
What it assumes
Assumes familiarity with Python files and built-in data structures while teaching JSON-to-Python conversion.
What you can do after
Build JSON-processing scripts that load, transform, analyze, and write structured data using Python's standard library.
How it connects
Connects JSON with Python lists, dicts, the json module, files, CSV, XML, and glob.

Also explained in

Compare how 35 books explain JSON →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.