简体   繁体   中英

Retrieve JSON string from pydantic Json type

I have a pydantic model as follows.

from pydantic import Json, BaseModel
class Foo(BaseModel):
    id: int
    bar: Json

Foo.bar can parse JSON string as input and store it as a dict which is nice.

foo = Foo(id=1, bar='{"foo": 2, "bar": 3}')
type(foo.bar) #outputs dict

And if i want the entire object to be a dict I can do

foo.dict()
#outputs
{'id': 1, 'bar': {'foo': 2, 'bar': 3}}

But how can I export bar as JSON string as following

{'id': 1, 'bar': '{"foo": 2, "bar": 3}'}

I want to write JSON back into the database.

Pydantic author here.

There's currently no way to do that without calling json.dumps(foo.bar) . You could make that a method on Foo if you liked, which would be easier to use but require the same processing.

If performance is critical, or you need the exact same JSON string you started with (same spaces etc.) You could do one of the following:

  • Make bar a string field but add a validator to check it's valid JSON
  • create a custom data type to parse the JSON but also keep a reference to the raw JSON string

Do you want to convert the nest to string?

x = {'id': 1, 'bar': str({'foo': 2, 'bar': 3})}

gives

{'id': 1, 'bar': "{'foo': 2, 'bar': 3}"}

The workaround that solved the problem in my scenario was to inherit BaseModel and override dict method.

class ExtendedModel(BaseModel):
    def dict(self, json_as_string=False, **kwargs) -> dict:
        __dict = super().dict(**kwargs)
        if json_as_string:
            for field, _ in self.schema()['properties'].items():
                if _.get('format') == 'json-string' and field in __dict :
                    __dict[field] = json.dumps(getattr(self, field))
        return __dict
 

self.__field__ wouldn't specify if the field's type is actually Json. It was returning as Any. So I used this approch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM