JSON Converter · Tutorial
How to parse a weather API response with Pydantic
8 min readintermediateUpdated
Your Python script reads a weather API and digs through nested dictionaries with string keys. This tutorial generates Pydantic models from a sample response, shows how to parse the JSON into typed objects, and improves the models so dates become datetime values.
What you need
- The JSON Converter with Python chosen under Convert to
- A sample API response, or the forecast from the Try it button
- Python 3.10+ with Pydantic 2 (
pip install pydantic)
Steps
Paste the response and name it
Paste the JSON and type
Forecastas the Root type name. Keep Pydantic model as the style. You get four classes:Location,Current,DailyandForecast, written so each class appears before the classes that use it.Look at the renamed fields
The API uses camelCase, so
feelsLikebecamefeels_like: float = Field(alias="feelsLike"). Your code uses the Python name, and Pydantic reads the JSON key through the alias.Spot the optional field
Only the second day has an
alert, soDailyhasalert: str | None = None. Days without an alert will parse fine, withalertset toNone.Parse the JSON
Save the code as
models.pyand parse the response in one call. Pydantic checks every field and raises a clearValidationErrorif the API ever sends something unexpected.from models import Forecast forecast = Forecast.model_validate_json(response_text) print(forecast.current.feels_like) print([day.max for day in forecast.daily])Make dates real dates
updated_atanddateare typed asstr. Change them todatetimeanddate(import them from thedatetimemodule). Pydantic converts ISO strings automatically, so you can compare and format them without parsing by hand.Write it back out
To send the data on as JSON with the original key names, use
forecast.model_dump_json(by_alias=True).
Try it yourself
Opens the JSON Converter with this tutorial's sample loaded.
Common mistakes
- Building objects with the Python names
Current(feels_like=17.9)fails by default, because Pydantic expects the alias. Either passfeelsLike=17.9, or addmodel_config = ConfigDict(populate_by_name=True)to the class.- Integers that are sometimes decimals
humiditywas a whole number in the sample, so it is typedint. If the API can send72.5, change it tofloat, or Pydantic will reject the value.- Pydantic version 1
- The generated code uses Pydantic 2 methods such as
model_validate_json. On version 1, useparse_rawinstead, or upgrade.
Next steps
Go back to the JSON Converter, or keep going with one of these:
FAQ
Can I use dataclasses instead?
Yes, choose dataclass in Style. You will need to build nested objects yourself, because dataclasses don't convert dicts into classes.
Why does a field shadow a built-in like min?
The JSON key is min, so the attribute is too. It works fine on a model; rename it with an alias if you prefer.