[英]Retrieve JSON string from pydantic Json type
I have a pydantic model as follows.我有一个 pydantic model 如下。
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.bar 可以将 JSON 字符串解析为输入并将其存储为一个很好的字典。
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如果我想让整个 object 成为一个
dict
,我可以做到
foo.dict()
#outputs
{'id': 1, 'bar': {'foo': 2, 'bar': 3}}
But how can I export bar
as JSON string as following但是如何将
bar
导出为 JSON 字符串,如下所示
{'id': 1, 'bar': '{"foo": 2, "bar": 3}'}
I want to write JSON back into the database.我想将 JSON 写回数据库。
Pydantic author here. Pydantic 作者在这里。
There's currently no way to do that without calling json.dumps(foo.bar)
.如果不调用
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.如果您愿意,您可以在
Foo
上创建一个方法,这将更容易使用但需要相同的处理。
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:如果性能至关重要,或者您需要与开头完全相同的 JSON 字符串(相同的空格等),您可以执行以下操作之一:
bar
a string field but add a validator to check it's valid JSONbar
设为字符串字段,但添加验证器以检查其是否有效 JSONDo 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.在我的场景中解决问题的解决方法是继承 BaseModel 并覆盖
dict
方法。
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. self.__field__
不会指定字段的类型是否实际上是 Json。 It was returning as Any.它以 Any 的形式返回。 So I used this approch.
所以我使用了这个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.