Library contents

Python json.loads and JSONDecodeError

json.loads converts a JSON document to Python objects. For a JSON object, a dictionary membership test distinguishes an absent key from a key holding zero.

A simple example

json.loads and JSONDecodeError

  1. Start with JSON text {"n":2}
  2. Do this Decode and read field n
  3. Result Number 2
Decoding turns the text representation into an object or record with a numeric field.

Syntax

Python syntax
record = json.loads(text)
Run this example in Python

Save the program as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Decode an optional numeric field

A dataset includes a missing or optional measurement alongside actual numerical values. Make the missing-value policy explicit so a valid zero is not discarded or silently replaced.

First output line0
lesson.py
import json

for text in ('{"qty": 0}', '{}', '{"qty":}'):
    try:
        record = json.loads(text)
        print(record["qty"] if "qty" in record else "unspecified")
    except json.JSONDecodeError:
        print("invalid JSON")
Output
0
unspecified
invalid JSON

A syntax error raises JSONDecodeError. Successful decoding establishes syntax only, so this example expects an object with a numeric qty when that member exists.

Python documentation for json.loads and JSONDecodeError

Advertisements

Read a locker report

A locker controller sends the number of free doors as JSON. Decode the JSON record before reading its count field. Which numeric count reaches the desk?

Given{"count":4}
Worked result4

Record an empty tray

A sorter sends an explicit count of zero for an empty tray. Decode the JSON record before reading its count field. Which numeric count reaches the desk?

Given{"count":0}
Worked result0