Skip to main content

The Language APIs Speak

APIs exchange data as JSON — text like {"id": 1, "name": "Ana"}. Python's json module translates in both directions: json.dumps turns Python data into JSON text, json.loads parses JSON text into Python data.

There is no mapping layer to configure: the keys are the field names, as written. A dataclass gives a record a fixed shape, and dataclasses.asdict turns it into a plain dict ready for json.dumps — rename keys by hand when the API needs a different spelling.


From Python Data to JSON

json.dumps produces one-line JSON for machines; json.dumps(..., indent=2) produces readable JSON for humans and logs. Nothing is dropped automatically — when an empty field should stay out of the JSON, delete it from the dict before dumping.

One line and pretty

Ana has no email, and the helper removes the empty field from her dict — her JSON stays clean. Ben's full record prints indented.

Prompt
Write a Python program with a User dataclass whose email field defaults to empty. Dump a user without an email on one line after removing the empty field from the dict, and a full user with json.dumps and indent=2, printing both JSON results.
Output: complete Python program

From JSON to Python Data

json.loads parses JSON into plain Python data — dicts, lists, strings, numbers. Unknown keys are not thrown away: everything in the JSON ends up in the dict, and a typed record is built from just the fields it needs. Bad JSON raises json.JSONDecodeError — catch it; it is the signal that the text was not JSON at all.

Loads and the extra key

The JSON carries an extra key that the User dataclass does not have — json.loads keeps it in the dict, and the dataclass simply picks the two fields it wants. Broken JSON, on the other hand, raises a real error.

Prompt
Write a Python program that parses a JSON string carrying an extra unknown key with json.loads, printing the dict that keeps the extra key and a typed User dataclass built from the fields it needs, then tries to parse broken JSON and prints the JSONDecodeError.
Output: complete Python program

Nested Data

Real API payloads nest: an order carries its user and a list of items. Dataclasses inside dataclasses and lists map to JSON objects and arrays automatically — asdict walks the whole structure.

An order with a user inside

The nested User dataclass becomes a nested JSON object, the items list becomes a JSON array — the shape of the Python data is the shape of the JSON.

Prompt
Write a Python program with an Order dataclass containing an id, a list of item names and a nested User dataclass. Turn one order into a dict with dataclasses.asdict and print it with json.dumps and indent=2 to show nested objects and arrays.
Output: complete Python program