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
- Start with JSON text {"n":2}
- Do this Decode and read field n
- Result Number 2
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.
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")
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
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?
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?