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 › serialization
Serialization - Pydantic Validation
The serialize_as_any runtime setting can be used to serialize model data with or without duck typed serialization behavior. serialize_as_any can be passed as a keyword argument to the various serialization methods (such as model_dump() and ...
Discussions

python - pydantic convert to jsonable dict (not full json string) - Stack Overflow
Thanks for the clear answer, really don't get why the pydantic docs are so verbose. They tell you everything but what you want to know. 2023-09-10T16:30:58.033Z+00:00 ... DO NOT follow @David 天宇 Wong's advice and use model_dump_json() directly. That gives you a JSON string. More on stackoverflow.com
🌐 stackoverflow.com
How to json serialize list of BaseModels
Question Hi I am trying to create a list of BaseModel objects and then convert that list to a json string. However when I use json.dumps(my_list) I get TypeError: Object of type User is not JSON se... More on github.com
🌐 github.com
4
5
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
Using Pydantic structured outputs in batch mode
Hello everyone, I’m having some trouble using Pydantic structured outputs in batch mode. The following is a toy example outlining my problem. import json from openai import OpenAI from pydantic import BaseModel, Field client = OpenAI() fruits = ["apple", "banana", "orange", "strawberry"] ... More on community.openai.com
🌐 community.openai.com
1
2
September 25, 2024
🌐
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 › models
Models - Pydantic Validation
One of the primary ways of defining schema in Pydantic is via models. Models are simply classes which inherit from BaseModel and define fields as annotated attributes. You can think of models as similar to structs in languages like C, or as ...
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json
JSON - Pydantic Validation
There is some overhead to looking up the cache, which is normally worth it to avoid constructing strings. However, if you know there will be very few repeated strings in your data, you might get a performance boost by disabling this setting with cache_strings=False. ... pydantic.main.BaseModel.model_dump_json pydantic.type_adapter.TypeAdapter.dump_json pydantic_core.to_json
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
This is similar to the field level field_title_generator, but the ConfigDict option will be applied to all fields of the class. ... import json from pydantic import BaseModel, ConfigDict class Person(BaseModel): model_config = ConfigDict( field_title_generator=lambda field_name, field_info: field_name.upper() ) name: str age: int print(json.dumps(Person.model_json_schema(), indent=2)) """ { "properties": { "name": { "title": "NAME", "type": "string" }, "age": { "title": "AGE", "type": "integer" } }, "required": [ "name", "age" ], "title": "Person", "type": "object" } """
Find elsewhere
🌐
DZone
dzone.com › coding › languages › mastering json serialization with pydantic
Mastering Json Serialization With Pydantic
December 14, 2023 - To translate JSON into a Pydantic model, Pydantic offers two methods: 'parse_obj' and 'parse_raw'.
🌐
Python⇒Speed
pythonspeed.com › articles › pydantic-json-memory
Loading Pydantic models from JSON without running out of memory
May 22, 2025 - But it would certainly be possible for Pydantic to internally work more like ijson, and to add the option for using __slots__ to BaseModel. The end result would use far less memory, while still benefiting from Pydantic’s faster JSON parser.
🌐
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

🌐
Pydantic
docs.pydantic.dev › 2.3 › usage › serialization
Serialization - Pydantic
The one exception to sub-models being converted to dictionaries is that RootModel and its subclasses will have the root field value dumped directly, without a wrapping dictionary. This is also done recursively. ... from typing import Any, List, Optional from pydantic import BaseModel, Field, Json class BarModel(BaseModel): whatever: int class FooBarModel(BaseModel): banana: Optional[float] = 1.1 foo: str = Field(serialization_alias='foo_alias') bar: BarModel m = FooBarModel(banana=3.14, foo='hello', bar={'whatever': 123}) # returns a dictionary: print(m.model_dump()) #> {'banana': 3.14, 'foo':
🌐
GitHub
github.com › pydantic › pydantic › discussions › 4456
Serialisation and Dumping · pydantic/pydantic · Discussion #4456
Python objects - models are converted to dicts, nothing else is changed · JSON compatible python - objects are converted to dict, list, str, int, float, bool, None ... All these formats should be customisable via functions - obviously 2 and 3 should use the same customisation logic. The plan is to implement as much of this logic as possible in rust within pydantic-core.
Author   pydantic
Top answer
1 of 3
4

Simple and updated answer Pydantic +2

Using RootModel

from datetime import date, datetime

from pydantic import BaseModel, RootModel


class Car(BaseModel):
    model: str
    is_fast: bool
    buy_date: date
    buy_datetime: datetime
    max_speed: float


Cars = RootModel[list[Car]]
cars = Cars(
    [
        Car(
            model=f"G Wagon {i}",
            is_fast=i % 2 == 0,
            buy_date=datetime.now().date(),
            buy_datetime=datetime.now(),
            max_speed=i + 1337,
        )
        for i in range(2)
    ]
)
json_txt = cars.model_dump_json(indent=2)

print(json_txt)
[
  {
    "model": "G Wagon 0",
    "is_fast": true,
    "buy_date": "2025-01-27",
    "buy_datetime": "2025-01-27T14:41:04.559555",
    "max_speed": 1337.0
  },
  {
    "model": "G Wagon 1",
    "is_fast": false,
    "buy_date": "2025-01-27",
    "buy_datetime": "2025-01-27T14:41:04.560554",
    "max_speed": 1338.0
  }
]

https://docs.pydantic.dev/latest/concepts/models/#rootmodel-and-custom-root-types

2 of 3
1

I would like to know the answer too. But it didn't come, so I did my own experiments. Hope it helps.

Q1: Does dump_json() skips validation? A1: It looks like it just serializes. To get a correct output I had to use the TypeAdapter twice: first time to valdiate, then to serialize.

Q2: Problem with exclude= A2: Please read the Advanced include and exclude

Below is my little test program with mocked data:

from pydantic import BaseModel, TypeAdapter

class UserPydanticModel(BaseModel):
    name: str 
    passwd: str 
    demo: bool = True

users_from_db = [dict(name=f'usr{i}', passwd=f'pwd{i}') for i in range(3)]

ta = TypeAdapter(list[UserPydanticModel])
users = ta.validate_python(users_from_db)
dumped = ta.dump_json(users, exclude={'__all__': 'passwd'})

print(dumped)

# b'[{"name":"usr0","demo":true},{"name":"usr1","demo":true},{"name":"usr2","demo":true}]'
🌐
PyPI
pypi.org › project › json-schema-to-pydantic
json-schema-to-pydantic · PyPI
3 weeks 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
🌐
Sling Academy
slingacademy.com › article › how-to-serialize-pydantic-models-into-json
How to serialize Pydantic models into JSON - Sling Academy
December 14, 2023 - While model_dump_json() offers a JSON-encoded string, making it more suitable for data exchange between a server and a client, it might not be the most efficient method for internal data manipulation within your application. Pydantic allows customization of the serialization process by providing decorators: @field_serializer and @model_serializer, which can be used to define custom serialization logic for specific fields or the entire model.
🌐
Datasciencebyexample
datasciencebyexample.com › 2024 › 08 › 15 › convert-pydantic-model-to-json-objects
Simplifying Data Serialization with Pydantic, `.dict()` and `.json()` | DataScienceTribe
When working with data models in Python, Pydantic is a fantastic library that streamlines validation and serialization. One of its most powerful features is the ease with which you can convert Pydantic classes into JSON format. In this blog post, we’ll explore how to achieve this using the .dict() and .json() methods, understand their differences, and see how to exclude null keys from the output.