PYTHON / CHAPTER 14
JSON parsing and domain validation
AdvancedSeparate syntactic parsing from application rules.
By the end of this chapter
- Decode JSON into Python values
- Validate shape and numeric domains
- Handle boolean-versus-integer distinctions
The idea
json.loads converts JSON text into Python values, but successful decoding does not establish your application’s schema. A valid JSON document might be a list, null, or an object missing a required field. First check the outer shape, then required values, and finally domain constraints such as a nonnegative count. Return a new normalized record when downstream code should not retain arbitrary input fields.
In Python, bool is a subclass of int. A count validator that uses only isinstance(value, int) therefore accepts True and False. If the contract excludes booleans, check their exact type or reject them explicitly. Do not silently catch unrelated programming errors as invalid input. Parsing failures and domain failures are separate situations and should retain useful explanations.
import json
def parse_count(text):
data = json.loads(text)
if not isinstance(data, dict):
raise ValueError("object required")
n = data.get("count")
if type(n) is not int or n < 0:
raise ValueError("nonnegative integer required")
return {"count": n}
print(parse_count('{"count": 0, "extra": 9}')){'count': 0}The parser accepts zero, rejects booleans, and constructs only the permitted field.
Try it yourself
Validate a JSON list of records, returning the index and reason of the first invalid record.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open Python coding challengesCHECK YOUR UNDERSTANDING