new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Pydantic · all subjects

json parsing & performance

8 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

General file validation pattern with model_validate

Most file formats can be validated by first converting the file contents to a Python dictionary using the appropriate parser library, then calling model_validate(dict) on a Pydantic model.

Validate JSON string with model_validate_json

Use BaseModel.model_validate_json(json_string) to validate data from a JSON string. This method parses the JSON and validates it against the model schema.

Validate JSONL files by processing line by line

For .jsonl (JSON lines) files where each line is a separate JSON object, read the file with read_text().splitlines() and validate each line individually using model_validate_json(line) in a list comprehension.

Validate CSV data using csv.DictReader

To validate CSV files, use the Python csv module's DictReader to parse the file into dictionaries, then validate each row with model_validate(row).

Validate TOML files using tomllib

Use Python's tomllib module to load TOML data: tomllib.load(file) returns a dictionary that can be validated with model_validate(data).

Validate YAML files using PyYAML

Use the PyYAML library: yaml.safe_load(file) returns a dictionary that can be validated with model_validate(data).

Validate XML files by parsing element tree

Parse XML using xml.etree.ElementTree: ET.parse(filename).getroot() gets the root element. Convert to dictionary by iterating children: {child.tag: child.text for child in tree}. Then validate with model_validate(data).

Validate INI files using configparser

Use Python's configparser module: config.read(filename) loads the INI file. Access sections as dictionaries: config['SECTION_NAME']. Validate with model_validate(section_dict).

Give your agent this brain