smartyfy.mrindigi.com

Python Master Course V2 — 076. JSON Data

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 08 · LESSON 076 OF 200

JSON Data

Study time: 75–100 minutes · Prerequisites: functions, exceptions, pathlib and Lesson 75.

Course hub

Video lesson

Video not yet available. Reserved for a verified lesson video URL/player.

Learning outcomes

Serialize and parse JSON safely. You will also identify failure cases, predict outputs, apply the concept in a small application, and test the result.

Concepts and detailed reasoning

A robust file or data pipeline has five distinct stages: acquire data, validate structure, convert values, transform records, and present or store results. Keep these stages separate. For every stage define what happens when input is empty, malformed, inaccessible or unexpectedly large. A reliable program should never silently discard important records.

Design approach: write a function that accepts explicit inputs and returns a documented result; isolate filesystem effects in a thin boundary layer; catch only errors you can meaningfully handle; preserve source data until output is validated. For large files, stream records instead of loading everything into memory.

Security: never treat external filenames, file contents or serialized objects as trusted instructions. Restrict file operations to authorized directories and avoid deserializing executable formats from unknown sources.

Understand and apply: JSON Data

JSON is a data format, not a Python object

JSON lets programs exchange a small, language-independent set of values. A JSON object becomes a Python dictionary, an array becomes a list, strings remain strings, and true, false and null become True, False and None. JSON numbers become int or float by default. The spelling matters: JSON uses double-quoted property names and lowercase literals. A printed Python dictionary is therefore not a reliable JSON document.

Use json.loads(text) to decode a string and json.dumps(value) to produce a string. The versions without s, load and dump, work with an open file. Serialization changes representation; it does not save a file unless you explicitly write one. Likewise, decoding does not prove that required keys, types or permitted values are present. That second step is validation.

Python example

import json
payload = {"name": "Café", "active": True, "tags": ["python"], "note": None}
text = json.dumps(payload, ensure_ascii=False, sort_keys=True)
print(text)
restored = json.loads(text)
print(restored["active"], restored["note"] is None)

Expected output

{"active": true, "name": "Café", "note": null, "tags": ["python"]}
True True

The encoder walks the nested structure and translates supported values. ensure_ascii=False keeps Unicode characters readable; it does not select a file encoding. Open a real text file with encoding="utf-8". Dictionary keys should be strings for a predictable round trip, and tuples become arrays, which decode as lists. Sets, dates and Decimal values need an explicit representation policy rather than a catch-all conversion that hides their meaning.

A small configuration contract

Suppose a configuration may contain a retry count and a debug switch. Missing optional keys receive documented defaults, but a supplied invalid value must be rejected. In particular, bool is a subclass of int in Python, so use an exact integer check when true must not mean one retry. Rejecting unknown keys catches spelling errors such as retries_count before they silently disable intended settings.

Python example

import json

def read_config(text):
    data = json.loads(text)
    if not isinstance(data, dict):
        raise ValueError("configuration must be an object")
    if set(data) - {"retries", "debug"}:
        raise ValueError("unknown configuration key")
    retries = data.get("retries", 2)
    debug = data.get("debug", False)
    if type(retries) is not int or not 0 <= retries <= 5:
        raise ValueError("retries must be an integer from 0 to 5")
    if type(debug) is not bool:
        raise ValueError("debug must be true or false")
    return {"retries": retries, "debug": debug}

print(read_config('{}'))
print(read_config('{"retries":0,"debug":true}'))

Expected output

{'retries': 2, 'debug': False}
{'retries': 0, 'debug': True}

Trace the loader in order: decode syntax, require an object, reject unexpected keys, obtain defaults, validate supplied values, return a normalized result. JSONDecodeError identifies malformed JSON; ValueError from the validator identifies valid JSON with an unacceptable shape or value. Keep those messages distinct at the application boundary so a learner can fix the actual cause.

For interoperable output, pass allow_nan=False to dumps so NaN and infinities are rejected. Strict input can use a parse_constant callback that raises for those nonstandard constants. Limit incoming document size before decoding because ordinary load/loads builds the full structure in memory. Test an empty object, valid overrides, a list instead of an object, a misspelled key, a boolean retry count and malformed syntax.

Progressive runnable Python example

Requires Python 3.10+. Run in a disposable practice folder. Save as lesson76.py and execute with python lesson76.py or python3.

import json
payload={'course':'Python','lesson':76,'active':True}
encoded=json.dumps(payload,sort_keys=True)
print(json.loads(encoded)['lesson'])
print('true' in encoded)

Expected output:

76
True

How to reason through the example

Identify which operation opens, parses, writes or transforms data. Trace each value from source to output. Note whether any file is created and whether repeated execution changes the result. Next, alter one value, predict the result, run the example and compare your prediction.

Guided practical project

Project brief: Create a JSON configuration loader that validates keys and uses safe defaults.

  1. Specify input format, accepted fields and error policy.
  2. Create a small sample dataset with three valid and two invalid records.
  3. Write a parser and validator that report errors with record numbers.
  4. Implement the transformation as a separate testable function.
  5. Write results to a different destination rather than overwriting source files.
  6. Test empty, malformed, boundary and ordinary cases.
  7. Document setup, expected output and recovery procedure.

Mastery requirements: at least three automated tests, explicit error handling and a reproducible example. This is an assignment, not a claim that the complete project has been executed on the website.

Common mistakes and debugging

  • Assuming the process working directory is the same as the script directory.
  • Relying on platform-dependent encodings.
  • Trusting records without checking required fields or types.
  • Overwriting input files before verifying transformed output.
  • Catching every exception and hiding the underlying failure.

Debug systematically: reproduce a failure with the smallest record, inspect the exception and offending input, correct the cause, and add a regression test.

Practice with explained answers

Make a prediction before opening each answer. Then trace the example and explain the result in your own words.

What is the difference between loads and load?

loads decodes a JSON string already in memory. load reads JSON from an open file-like object. Neither validates your application schema; both return Python values.

Why does json.loads("{'active': True}") fail?

That text uses Python syntax. JSON requires double quotes around the property and the literal true. The decoder raises JSONDecodeError before application validation begins.

Worked answer

import json
print(json.loads('{"active": true}')["active"])

Expected output

True
Should {"retries": true} pass the configuration validator?

No. JSON true becomes Python True, which satisfies isinstance(True, int). The exact check type(retries) is int deliberately rejects it, preserving a count-only contract.

Will a tuple survive a JSON round trip as a tuple?

No. It is serialized as a JSON array and decoded as a list. Use an explicit schema if reconstructing a special Python type is important.

Worked answer

import json
print(json.loads(json.dumps((1, 2))))

Expected output

[1, 2]
Why use allow_nan=False when exporting measurements?

NaN and Infinity are not standard JSON numbers. Rejecting them makes the failure explicit instead of sending a document that other systems may reject. Decide whether invalid measurements should be rejected or represented as null before serialization.

Mastery checkpoint

Demonstrate the sample, explain its output, implement the project, test three edge cases, and describe your error-handling policy. The video remains unavailable and learner completion is not account-synchronized.

Course hub · Previous lesson 75 in course hub · Continue with the next published lesson using the lesson navigation.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.