从 pydantic Json 类型检索 JSON 字符串

Jey*_*Jey 5 python pydantic

我有一个如下的 pydantic 模型。

from pydantic import Json, BaseModel
class Foo(BaseModel):
    id: int
    bar: Json
Run Code Online (Sandbox Code Playgroud)

Foo.bar 可以解析 JSON 字符串作为输入并将其存储为字典,这很好。

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

如果我希望整个对象成为dict我可以做的

foo.dict()
#outputs
{'id': 1, 'bar': {'foo': 2, 'bar': 3}}
Run Code Online (Sandbox Code Playgroud)

但如何导出bar为 JSON 字符串,如下所示

{'id': 1, 'bar': '{"foo": 2, "bar": 3}'}
Run Code Online (Sandbox Code Playgroud)

我想将 JSON 写回数据库。

SCo*_*vin 13

Pydantic 作者在这里。

目前没有办法在不调用 的情况下做到这一点json.dumps(foo.bar)。如果您愿意,可以将其设为 on 方法Foo,这会更容易使用,但需要相同的处理。

如果性能至关重要,或者您需要与开始时完全相同的 JSON 字符串(相同的空格等),您可以执行以下操作之一:

  • 创建bar一个字符串字段,但添加一个验证器来检查它的 JSON 是否有效
  • 创建自定义数据类型来解析 JSON,同时保留对原始 JSON 字符串的引用


小智 0

您想将嵌套转换为字符串吗?

x = {'id': 1, 'bar': str({'foo': 2, 'bar': 3})}
Run Code Online (Sandbox Code Playgroud)

给出

{'id': 1, 'bar': "{'foo': 2, 'bar': 3}"}
Run Code Online (Sandbox Code Playgroud)