Reputation: 11
I have a pydantic model with a 2D array that I’d like to pretty print when I dump it to a file with an indentation set at 4. For reference:
import json
from annotated_types import Len
from typing_extensions import Annotated
from pydantic import BaseModel, Field, ConfigDict
TwoDim = Annotated[
Sequence[float],
Len(min_length=2, max_length=2),
]
class Tester(BaseModel):
test_val: Sequence[TwoDim] = Field()
I have tried implementing a custom encoder and using the model’s ConfigDict:
# in the model definition
model_config = ConfigDict(
json_encoders={
TwoDim: NoIndentEncoder().encode
}
)
class NoIndentEncoder(json.JSONEncoder):
def encode(self, obj):
if isinstance(obj, list):
return f”[{‘, ‘.join([json.dumps(elem) for elem in obj])}]”
return super().encode(obj)
This almost gives me the right output (read as a json file):
{
“test_val”: [
“[0.0, 1.2]”,
“[3.0, 1.4]”,
…
]
}
But I don’t want each internal array to print with quotes.
Upvotes: 0
Views: 397
Reputation: 191
This may work for you:
import json
from pydantic.json import pydantic_encoder
json.dump(your_pydantic_model.model_dump(), file_obj, default=pydantic.encoder, indent=4)
Upvotes: 1