Guide

Read JSON in Python

Python's json module can decode JSON from a file or string into Python values. A reliable workflow separates reading the text, decoding its syntax, and checking the expected structure, so an unexpected document does not silently become trusted application input.

At a glance

File decoder
json.load
String decoder
json.loads

Overview

Python's json module can decode JSON from a file or string into Python values. A reliable workflow separates reading the text, decoding its syntax, and checking the expected structure, so an unexpected document does not silently become trusted application input.

1. Select the input

Use json.load with an opened text file when reading a document, or json.loads when the JSON is already a string. Choose the intended encoding when opening a file and keep its lifetime explicit.

2. Handle decoding errors

Catch the documented decoding exception at the boundary where invalid input is expected. Report which input could not be decoded without replacing the failure with a misleading empty or successful result.

3. Validate the values

After decoding, check the expected object or array shape, required keys, and value types. Valid JSON can still contain the wrong data for your task, so only proceed after these application checks pass.

Sources and review

MOOR's explanatory text is supported by the following source links.

  1. JSON encoder and decoder — Python
  2. Input and output — Python

Browse MOOR Knowledge