Pydantic: Serialize models with __root__

Created on 9 Aug 2019  路  2Comments  路  Source: samuelcolvin/pydantic

Question

  • Python version import sys; print(sys.version): 3.6
  • Pydantic version import pydantic; print(pydantic.VERSION): 0.30

How to serrialize models with __root__

from pydantic import BaseModel
from typing import List

class Pets(BaseModel):
    __root__: List[str]

pets = Pets(__root__=['dog', 'cat'])
print(pets.json())

result: {"__root__": ["dog", "cat"]}
How can I get ["dog","cat"]?

Change Feedback Wanted question

Most helpful comment

Just for future reference "["dog","cat"]" is ambiguous, it could be a python object or a JSON string without the quotes, best to be clear what you're taking about.

I guess json() should be changed as per v1 to serialize m.__root__ if it's defined that would fundamentally change it's behaviour from dict() but I think makes sense.

Anyone else, thoughts?

All 2 comments

pets.__root__

Just for future reference "["dog","cat"]" is ambiguous, it could be a python object or a JSON string without the quotes, best to be clear what you're taking about.

I guess json() should be changed as per v1 to serialize m.__root__ if it's defined that would fundamentally change it's behaviour from dict() but I think makes sense.

Anyone else, thoughts?

Was this page helpful?
0 / 5 - 0 ratings