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']}
🌐
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
Discussions

python - Initializing a pydantic dataclass from json - Stack Overflow
I'm in the process of converting existing dataclasses in my project to pydantic-dataclasses, I'm using these dataclasses to represent models I need to both encode-to and parse-from json. Here's an 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
Replacement for pydantic.json.pydantic_encoder
I think we need to do both here because according to the sqlalchemy documentation a "Python callable that will render a given object as JSON" is expected. As far as I understand, I get a python object from pydantic_core.to_jsonable_python. More on github.com
🌐 github.com
5
5
Python/Pydantic - using a list with json objects - Stack Overflow
The web-frameworks supporting Pydantic often jsonify such ItemList as a JSON array without intermediate __root__ keyword. ... For my own understanding, does the __root__ effectively change the 'root' character of the ItemList to those item in Item? Whereas, using each_item effectively creates a thing inside ItemList? Thanks. 2019-11-01T04:11:28.7Z+00:00 ... The docs lists this as a use case, so I prefer this, although it feels slighly un-pythonic ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
You can also implement __get_pydantic_json_schema__ to modify or override the generated json schema. Modifying this method only affects the JSON schema - it doesn't affect the core schema, which is used for validation and serialization. Here's an example of modifying the generated JSON schema: import json from typing import Any from pydantic_core import core_schema as cs from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler, TypeAdapter from pydantic.json_schema import JsonSchemaValue class Person: name: str age: int def __init__(self, name: str, age: int): self.name = name self.age
🌐
Python⇒Speed
pythonspeed.com › articles › pydantic-json-memory
Loading Pydantic models from JSON without running out of memory
May 22, 2025 - We’re going to start with a 100MB JSON file, and load it into Pydantic (v2.11.4). Here’s what our model looks like: from pydantic import BaseModel, RootModel class Name(BaseModel): first: str | None last: str | None class Customer(BaseModel): id: str name: Name notes: str # Map id to corresponding Customer: CustomerDirectory = RootModel[dict[str, Customer]]
🌐
Pydantic
docs.pydantic.dev › latest › concepts › serialization
Serialization - Pydantic Validation
Pydantic allows data to be serialized directly to a JSON-encoded string, by trying its best to convert Python values to valid JSON data. This is achievable by using the model_dump_json() method: from datetime import datetime from pydantic import ...
Find elsewhere
🌐
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

🌐
PyPI
pypi.org › project › json-schema-to-pydantic
json-schema-to-pydantic · PyPI
1 month ago - A Python library for automatically generating Pydantic v2 models from JSON Schema definitions
      » pip install json-schema-to-pydantic
    
Published   Mar 09, 2026
Version   0.4.11
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.

🌐
GitHub
github.com › brokenloop › jsontopydantic
GitHub - brokenloop/jsontopydantic: Web tool for generating Pydantic models from JSON objects · GitHub
JSON to Pydantic is a tool that lets you convert JSON objects into Pydantic models. JSON is the de-facto data interchange format of the internet, and Pydantic is a library that makes parsing JSON in Python a breeze.
Starred by 357 users
Forked by 12 users
Languages   TypeScript 53.9% | HTML 18.0% | Python 15.7% | CSS 12.4%
🌐
LangChain
python.langchain.com › docs › modules › model_io › output_parsers › pydantic
Pydantic (JSON) parser
TypedDict and JSON Schema require manual validation. See your provider’s integration page for supported methods and configuration options. Example: Message output alongside parsed structure · It can be useful to return the raw AIMessage object alongside the parsed representation to access response metadata such as token counts. To do this, set include_raw=True when calling with_structured_output: from pydantic import BaseModel, Field class Movie(BaseModel): """A movie with details.""" title: str = Field(description="The title of the movie") year: int = Field(description="The year the movie
🌐
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 - For generating Pydantic models from existing JSON Schema files, use datamodel-code-generator. This powerful tool by Koudai Aono supports multiple input formats and is actively maintained by the community: # Install the tool pip install ...
🌐
PyPI
pypi.org › project › json2python-models
json2python-models · PyPI
json2python-models is a Python tool that can generate Python models classes (pydantic, (sqlmodel, dataclasses, attrs) from JSON datasets.
      » pip install json2python-models
    
Published   Oct 24, 2024
Version   0.3.1