I think I arrive a little bit late to the party, but I think this answer may come handy for future users having the same question.

To convert the dataclass to json you can use the combination that you are already using using (asdict plus json.dump).

from pydantic.dataclasses import dataclass

@dataclass
class User:
  id: int
  name: str

user = User(id=123, name="James")
d = asdict(user)  # {'id': 123, 'name': 'James'
user_json = json.dumps(d)
print(user_json)  # '{"id": 123, "name": "James"}'

# Or directly with pydantic_encoder
json.dumps(user, default=pydantic_encoder)

Then from the raw json you can use a BaseModel and the parse_raw method.

If you want to deserialize json into pydantic instances, I recommend you using the parse_raw method:

user = User.__pydantic_model__.parse_raw('{"id": 123, "name": "James"}')
print(user)
# id=123 name='James'

Otherwise, if you want to keep the dataclass:

json_raw = '{"id": 123, "name": "James"}'
user_dict = json.loads(json_raw)
user = User(**user_dict)
Answer from Guillem on Stack Overflow
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json
JSON - Pydantic Validation
The JSON list is incomplete - it's missing a closing "] When allow_partial is set to False (the default), a parsing error occurs. When allow_partial is set to True, part of the input is deserialized successfully. This also works for deserializing partial dictionaries. For example: from pydantic_core import from_json partial_dog_json = '{"breed": "lab", "name": "fluffy", "friends": ["buddy", "spot", "rufus"], "age' dog_dict = from_json(partial_dog_json, allow_partial=True) print(dog_dict) #> {'breed': 'lab', 'name': 'fluffy', 'friends': ['buddy', 'spot', 'rufus']}
Discussions

Python/Pydantic - using a list with json objects - Stack Overflow
I have a working model to receive a json data set using pydantic. The model data set looks like this: data = {'thing_number': 123, 'thing_description': 'duck', 'thing_amount': 4.5... More on stackoverflow.com
🌐 stackoverflow.com
JSONtoPydantic - Generate Pydantic Models from JSON in the browser
Full credit for the actual model creation goes to the datamodel-code-generator project! More on reddit.com
🌐 r/Python
17
41
December 4, 2020
Generating json/dictionary from pydantic model
If you mean to generate it from an object, then use model.model_dump(...). It also provides options to choose which fields should be included https://docs.pydantic.dev/latest/concepts/serialization/ If you want to create the dict from the class itself, to for example document the defaults, then first create instance of the class and then use model_dump on that instance. More on reddit.com
🌐 r/learnpython
4
1
January 14, 2024
python - parse json file to Pydantic model - Stack Overflow
I created a model of Pydantic. But it does not convert and outputs an error Please tell me,what is wrong. classDTO: from pydantic import BaseModel,Field from typing import List,Dict from datetime i... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pydantic
docs.pydantic.dev › 2.0 › usage › types › json
JSON - Pydantic
It can also optionally be used to parse the loaded object into another type base on the type Json is parameterised with: from typing import Any, List from pydantic import BaseModel, Json, ValidationError class AnyJsonModel(BaseModel): json_obj: Json[Any] class ConstrainedJsonModel(BaseModel): json_obj: Json[List[int]] print(AnyJsonModel(json_obj='{"b": 1}')) #> json_obj={'b': 1} print(ConstrainedJsonModel(json_obj='[1, 2, 3]')) #> json_obj=[1, 2, 3] try: ConstrainedJsonModel(json_obj=12) except ValidationError as e: print(e) """ 1 validation error for ConstrainedJsonModel json_obj JSON input s
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
Note that this overrides the whole ... pydantic import BaseModel, WithJsonSchema MyInt = Annotated[ int, WithJsonSchema({'type': 'integer', 'examples': [1, 0, -1]}), ] class Model(BaseModel): a: MyInt print(json.dumps(Model.m...
Top answer
1 of 6
37

The following also works, and does not require a root type.

To convert from a List[dict] to a List[Item]:

items = parse_obj_as(List[Item], bigger_data)

To convert from JSON str to a List[Item]:

items = parse_raw_as(List[Item], bigger_data_json)

To convert from a List[Item] to a JSON str:

from pydantic.json import pydantic_encoder

bigger_data_json = json.dumps(items, default=pydantic_encoder)

or with a custom encoder:

from pydantic.json import pydantic_encoder

def custom_encoder(**kwargs):
    def base_encoder(obj):
        if isinstance(obj, BaseModel):
            return obj.dict(**kwargs)
        else:
            return pydantic_encoder(obj)
    return base_encoder


bigger_data_json = json.dumps(items, default=custom_encoder(by_alias=True))
2 of 6
30

To avoid having "each_item" in the ItemList, you can use the __root__ Pydantic keyword:

from typing import List
from pydantic import BaseModel

class Item(BaseModel):
    thing_number: int
    thing_description: str
    thing_amount: float

class ItemList(BaseModel):
    __root__: List[Item]    # ⯇-- __root__

To build the item_list:

just_data = [
    {"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56},
    {"thing_number": 456, "thing_description": "cow", "thing_amount": 7.89},
]
item_list = ItemList(__root__=just_data)

a_json_duck = {"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56}
item_list.__root__.append(a_json_duck)

The web-frameworks supporting Pydantic often jsonify such ItemList as a JSON array without intermediate __root__ keyword.

🌐
Reddit
reddit.com › r/python › jsontopydantic - generate pydantic models from json in the browser
r/Python on Reddit: JSONtoPydantic - Generate Pydantic Models from JSON in the browser
December 4, 2020 -

https://jsontopydantic.com

Hi there! I built this over the weekend and figured someone other than myself might find it useful.

Like many who work with REST APIs in Python, I've recently fallen in love with Pydantic. If you haven't heard of Pydantic, it's a data validation and parsing library that makes working with JSON in Python quite pleasant.

I needed a quick way to generate a Pydantic model from any given sample of JSON, and hacked together this application to do so. You can paste in a valid JSON string, and you'll get a valid Pydantic model back.

This is helpful if you're working with poorly documented APIs, really big objects, or have lots of edge cases to catch.

Check it out and let me know what you think!

Code -> https://github.com/brokenloop/jsontopydantic

Find elsewhere
🌐
Pydantic
docs.pydantic.dev › latest › concepts › serialization
Serialization - Pydantic Validation
This is achievable by using the model_dump_json() method: from datetime import datetime from pydantic import BaseModel class BarModel(BaseModel): whatever: tuple[int, ...] class FooBarModel(BaseModel): foo: datetime bar: BarModel m = ...
🌐
Superjson
superjson.ai › home › blog › how to generate pydantic models from json: complete python developer guide
How to Generate Pydantic Models from JSON: Complete Python Developer Guide
August 12, 2025 - Learn how to automatically generate Pydantic models from JSON data with validation, type hints, and schema generation. Includes tools, best practices, and real-world examples.
🌐
PyPI
pypi.org › project › json-schema-to-pydantic
json-schema-to-pydantic · PyPI
1 month ago - from json_schema_to_pydantic import ... references ) try: model = create_model(schema) except TypeError as e: print(f"Invalid type in schema: {e}") except ReferenceError as e: print(f"Invalid reference: {e}")...
      » pip install json-schema-to-pydantic
    
Published   Mar 09, 2026
Version   0.4.11
🌐
GitHub
github.com › brokenloop › jsontopydantic
GitHub - brokenloop/jsontopydantic: Web tool for generating Pydantic models from JSON objects · GitHub
Web tool for generating Pydantic models from JSON objects - brokenloop/jsontopydantic
Starred by 357 users
Forked by 12 users
Languages   TypeScript 53.9% | HTML 18.0% | Python 15.7% | CSS 12.4%
🌐
Pydantic
docs.pydantic.dev › latest › integrations › datamodel_code_generator
datamodel-code-generator - Pydantic Validation
# generated by datamodel-codegen: # filename: person.json # timestamp: 2020-05-19T15:07:31+00:00 from __future__ import annotations from typing import Any from pydantic import BaseModel, Field, conint class Pet(BaseModel): name: str | None = None age: int | None = None class Person(BaseModel): first_name: str = Field(description="The person's first name.") last_name: str = Field(description="The person's last name.") age: conint(ge=0) | None = Field(None, description='Age in years.') pets: list[Pet] | None = None comment: Any | None = None
🌐
PyPI
pypi.org › project › json2python-models
json2python-models · PyPI
r""" generated by json2python-models v0.2.0 at Mon May 4 17:46:30 2020 command: /opt/projects/json2python-models/venv/bin/json2models -f pydantic -s flat -m DriverStandings driver_standings.json """ from pydantic import BaseModel, Field from typing import List from typing_extensions import Literal class DriverStandings(BaseModel): season: int round_: int = Field(..., alias="round") DriverStandings: List['DriverStanding'] class DriverStanding(BaseModel): position: int position_text: int = Field(..., alias="positionText") points: int wins: int driver: 'Driver' = Field(..., alias="Driver") constr
      » pip install json2python-models
    
Published   Oct 24, 2024
Version   0.3.1
🌐
Stack Overflow
stackoverflow.com › questions › 71768023 › parse-json-file-to-pydantic-model
python - parse json file to Pydantic model - Stack Overflow
Traceback (most recent call last): File "main.py", line 73, in <module> students = pydantic.parse_file_as(path='192.json', type_=classDTO.StudentsDTO) File "pydantic\tools.py", line 60, in pydantic.tools.parse_file_as File "pydantic\tools.py", line 38, in pydantic.tools.parse_obj_as File "pydantic\main.py", line 331, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 424 validation errors for ParsingModel[StudentsDTO] __root__ -> __root__ -> 0 -> attestations -> __root__ -> 18 -> value none is not an allowed value (type=type_error.none.not_allowed) __root__ -> __root__ -> 0 -> attestations -> __root__ -> 19 -> value none is not an allowed value (type=type_error.none.not_allowed) __root__ -> __root__ -> 0 -> attestations -> __root__ -> 20 -> value none is not an allowed value (type=type_error.none.not_allowed) ...
🌐
DZone
dzone.com › coding › languages › mastering json serialization with pydantic
Mastering Json Serialization With Pydantic
December 14, 2023 - Enums are a way to represent a set of named values, and Pydantic allows the use of Enum types within its models. Pedantic automatically converts the Enum value to its corresponding string representation during JSON serialization. ... from enum import Enum class Department(str, Enum): it = "Information Technology" hr = "Humar Resource" acct = "Accounts" user = User(id=1, name="Test user", age = 12, dept=Department.it) user.json() //{"id":1,"name":"Test user","age":12,"dept":"Information Technology"}
🌐
Python⇒Speed
pythonspeed.com › articles › pydantic-json-memory
Loading Pydantic models from JSON without running out of memory
May 22, 2025 - It also requires us to do a bit more of the work of parsing the JSON, but anything below the top-level JSON object or list can be done by Pydantic. We’re creating a lot of Python objects, and one way to save memory on Python objects is to use “slots”. Essentially, slots are a more efficient ...
🌐
DEV Community
dev.to › arenasbob2024cell › json-to-python-complete-guide-to-dataclasses-pydantic-and-json-parsing-24db
JSON to Python: Complete Guide to Dataclasses, Pydantic, and JSON Parsing - DEV Community
February 27, 2026 - class Address(BaseModel): street: str city: str zip: str class Customer(BaseModel): name: str email: str address: Address # Nested model — validated automatically class Order(BaseModel): order_id: str customer: Customer items: list[str] total: float # Full nested validation from dict order = Order.model_validate(json.loads(json_string)) print(order.customer.address.city) from pydantic import BaseModel from typing import Optional class Profile(BaseModel): id: int name: str bio: Optional[str] = None # null → None age: int | None = None # Python 3.10+ union syntax score: float = 0.0 # default value for missing fields
🌐
Jsonjet
jsonjet.com › json-to-pydantic-converter
JSON to Pydantic Model Converter | JSON Jetstream | JSON Jetstream
Paste your JSON below to get started. ... Generate Python Pydantic models from your JSON data.