Choose a Data Format for Its Contract
Core idea
Choose a serialization format by data shape, interoperability, fidelity and trust. JSON is useful for nested cross-language records; CSV for flat tables; TOML or INI for configuration; XML for established element-based interfaces; pickle only for trusted Python-specific persistence. Explicit schemas and migration policies matter more than filename extensions.
import jsonrecord = {"values": (3, 5)}result = json.loads(json.dumps(record))print(type(result["values"]).__name__)A cross-language array is not a Python tuple; document that conversion in the contract.
Check a schema version
import jsondef read_record(text): data = json.loads(text) if not isinstance(data, dict) or type(data.get("version")) is not int or data["version"] != 1: raise ValueError("unsupported schema") if not isinstance(data.get("label"), str): raise ValueError("invalid label") return data["label"]print(read_record('{"version":1,"label":"north"}'))try: read_record('{"version":2,"label":"north"}')except ValueError: print("rejected")The application verifies the known version and label type before using the data.
Common mistake
No format automatically provides authentication, complete validation, or unlimited safe parsing. Set resource limits, explicit types and compatibility rules appropriate to the application.
Practice
For a flat sales report, nested API payload and human-edited settings, choose a format and explain what validation and conversion each requires.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Format selection and schema
Check your understanding of data format selection.
What is printed?
import jsonprint(type(json.loads("[1,2]")).__name__)What is printed?
import csvprint(next(csv.reader(["7,8"])))Which format best fits a flat table exchanged with spreadsheet software?
What is a schema version useful for?