liveBook · Manning

Json

As explained in Python Workout, Second Edition

The json module is Python's standard-library module for encoding Python objects as JSON and decoding JSON into Python objects.

Use Python’s standard-library json module to move between JSON-formatted data and Python objects. JSON is a data representation rather than a Python data type, so reading or creating it requires conversion. section 6.22 section 6.23

Choose the operation that matches the input:

  • Use json.load with a file object containing one JSON value, such as an array. section 6.23
  • Use json.loads when JSON text is already in a string, such as a line read from a file. section 6.23
  • Use json.dump or json.load to move between Python data structures and JSON-formatted file data. section 6.30

Analyze JSON score files

Implement print_scores(directory) by finding matching .json files, loading each file’s array of dictionaries, collecting subject scores in a nested dictionary, and printing each class’s minimum, maximum, and average. Remember that valid JSON uses double quotes, not Python-style single quotes. section 6.22 section 6.23

[{"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}
]

A JSON array of student dictionaries becomes a Python combination of built-in structures that can be traversed and aggregated. section 6.22

How Python Workout, Second Edition covers it

How deep it goes
Explains load, loads, dump, file discovery, and nested aggregation through a multi-file score-analysis exercise.
Examples
Uses class score files containing arrays of subject dictionaries and summarizes each subject’s minimum, maximum, and average.
What it assumes
Assumes familiarity with Python files, lists, dictionaries, iteration, and functions while reinforcing built-in structures over custom classes.
What you can do after
Builds a multi-file JSON score analyzer using json.load, glob, nested dictionaries, and aggregate calculations.
How it connects
Connects JSON with files, built-in Python data structures, XML, CSV, and glob-based filename matching.

Also explained in

Compare how 4 books explain json →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.