Lesson · Standard Data Formats
JSON
55 min readJSON
JSON is a language-neutral text format with a smaller type system than Python. Serialization requires explicit decisions about unsupported objects, precision, validation, and trust.
Learning goals
- Parse a JSON string with
json.loadsand list the Python types the result can contain. - Serialize Python data with
json.dumpsand control formatting withindentandsort_keys. - Explain why
True,None, and tuples have specific JSON counterparts and what happens to unsupported types. - Read and write JSON files with the
loadanddumpvariants and state the difference from the string versions. - Predict when parsing or serialization raises (
json.JSONDecodeError,TypeError) and why.
Mental model
The round trip is the lesson: loads produces only a small set of built-in types, your code works with those, and dumps turns them back into text. Anything outside that type set (dates, sets, custom classes) must be converted at the boundary, and every value read from another system is untrusted until validated.
Mental model
read it top to bottom
JSON text → json.loads → Python values (dict, list, str, int, float, bool, None) ↓ modify and validate json.dumps → JSON text
Core idea
JSON is a data interchange format with a deliberately small type system, and json is the translator between that system and Python's. The translation is one-to-one for dicts, lists, strings, numbers, booleans, and None, and everything else is your decision: flatten it, encode it, or reject it. The same division applies to trust: parsing proves syntax only, so validation is still required before the data drives behavior.
json.loads
json.loads() parses a JSON string into Python values. Parsing succeeds only for JSON syntax and produces JSON-compatible Python types rather than arbitrary application objects.
json.dumps
json.dumps() serializes compatible Python values to JSON text. Custom objects need an explicit conversion policy rather than implicit magic.
File serialization
File serialization converts in-memory values into a representation that can cross a file, network, or process boundary. Consider compatibility, size, trust, and how much type information the format preserves.
Python-to-JSON type mapping
JSON has a smaller type system than Python. Dictionaries need string-like keys for interoperable JSON, tuples become arrays, and objects such as dates or Decimal values need an explicit encoding policy.
Custom encoding overview
Custom JSON encoding should convert domain objects to ordinary JSON-compatible values at a clear boundary. Avoid leaking arbitrary object internals into a wire format.
Walkthrough
payloadis a JSON string containing an object with a string and an array;json.loadsparses it into a Pythondictwhose"scores"value is alist, and every key is astr.data["active"] = Truemutates the parsed dict;Truewill serialize back to JSON'strue, because the mappings line up one-to-one for the basic types.json.dumps(data, indent=2, sort_keys=True)returns a formatted string:indent=2adds newlines and two-space nesting, andsort_keys=Trueorders the keys alphabetically (active,name,scores).- Predict before running: the exact printed text including key order and indentation, then what
json.dumpsraises ifdata["when"]were set to adatetimeobject.
Experiments to try
- Parse
'{"n": 1, "n": 2}'and print the result; duplicates are allowed by the parser and the last value wins, which is a useful warning about untrusted input. - Encode the dict with
sort_keys=TrueandFalseand diff the two strings; note that key order is not meaningful in JSON but is visible in the text. - Try
json.dumps({1, 2, 3})and read theTypeError; then passdefault=listand observe what the set becomes. - Parse a string with an invalid trailing comma and print the
json.JSONDecodeErrorattributesmsg,pos, andlinenoto see the diagnostic information the exception carries.
Common mistakes
- Assuming parse success means the shape is right:
loadsaccepts any valid JSON, so a missing key or a string where a number was expected fails later, at the point of use, unless the data is validated at the boundary. - Letting non-ASCII characters surprise you:
json.dumpsescapes them by default (ensure_ascii=True), which is correct JSON but not what people expect when reading the output;ensure_ascii=Falsewrites the characters directly. - Using
json.dumpandjson.dumpsinterchangeably: one writes to a file object and returnsNone, the other returns a string, so mixing them up loses the write or raisesTypeError. - Treating
NaNandInfinityas portable: Python emits and accepts them by default, but they are not valid JSON for other parsers, soallow_nan=Falseturns them into an error at serialization time.
Practice: Easy
- Parse
'{"name": "Ada", "scores": [98, 99]}', add"active": True, and dump withindent=2, sort_keys=True; write the expected output before running. - Print
type()of each value extracted from the parsed payload and label it with the JSON source type. - Serialize
{"scores": (98, 99)}and explain why the output contains an array although the input held a tuple.
Practice: Medium
- Round-trip a dict through
dumpsthenloadsand assert equality; then add asetvalue and record the exactTypeErrorbefore fixing it with a conversion function. - Write
save(path, data)andload(path)usingjson.dumpandjson.loadwithencoding="utf-8"; test both on a temporary file and confirm a non-ASCII name survives the round trip when dumping withensure_ascii=False. - Compare nested access with
.get()chains versus a try/except around the whole parse-and-extract block; decide which failure mode gives better messages for a missing key.
Practice: Hard
- Design an encoding policy for a record type (for example a
datetimeand aDecimalfield) and implement it withdefault=on dump plus explicit validation on load. Document what a consumer must do to decode it. - Build a validating loader: given a schema-like description (required keys and types), load a JSON payload and report every violation instead of the first one. Test it with two invalid documents.
- Compare
json.dumpsoutput with and withoutseparators=(",", ":")on a large nested structure; measure both lengths and decide which form belongs on the wire versus in a debug log.
Lesson checklist
- I can parse JSON text and name the Python types that come back.
- I can serialize a structure with chosen formatting and predict unsupported-type errors.
- I can explain why parsing proves syntax but not shape, and where validation belongs.
- I can choose between the string and file variants of
loadanddump.
Remember
JSON is a small, language-neutral type system, and the `json` module is a one-to-one translator for its basic kinds of value; anything beyond them needs a conversion policy you write. Two habits keep the boundary clean: validate the parsed structure before deeper code touches it, and serialize with an explicit policy for the types JSON does not have.
Interview angles
What is the main purpose of **json.loads**?+
json.loads() parses a JSON string into Python values. Parsing succeeds only for JSON syntax and produces JSON-compatible Python types rather than arbitrary application objects.
What should you pay attention to when using **json.dumps**?+
json.dumps() serializes compatible Python values to JSON text. Custom objects need an explicit conversion policy rather than implicit magic.
How does **File serialization** fit into this lesson?+
File serialization converts in-memory values into a representation that can cross a file, network, or process boundary. Consider compatibility, size, trust, and how much type information the format preserves.
Which operation writes to a file, `json.dump` or `json.dumps`, and what does each return?+
json.dump(obj, file) writes directly to a file object and returns None; json.dumps(obj) returns the JSON string. The same split holds for load (reads from a file) and loads (parses a string).