gpt4 book ai didi

Is it possible to get pydantic v2 to dump json with sorted keys?(有没有可能让PYDINTIC v2转储带有排序关键字的json?)

转载 作者:bug小助手 更新时间:2023-10-25 13:26:56 25 4
gpt4 key购买 nike



In the pydantic v1 there was an option to add kwargs which would get passed to json.dumps via **dumps_kwargs. However, in pydantic v2 if you try to add extra kwargs to BaseModel.json() it fails with the error TypeError: `dumps_kwargs` keyword arguments are no longer supported.

在pydtic v1中,有一个添加kwargs的选项,这些kwargs将通过**Dumps_kwargs传递给json.ump。然而,在PYDNIC v2中,如果您尝试向BaseModel.json()添加额外的kwarg,则会失败,并显示错误TypeError:不再支持`Dumps_kwargs`关键字参数。


Here is example code with a workaround using dict()/model_dump(). This is good enough as long as the types are simple, but it won't work for the more complex data types that pydantic knows how to serialize.

以下是使用dict()/Model_Dump()解决办法的示例代码。只要类型很简单,这就足够好了,但是它不适用于更复杂的数据类型,因为它知道如何序列化。


Is there a way to get sort_keys to work in pydantic v2 in general?

有没有一种方法可以让SORT_KEYS在PYDNIC v2中正常工作?


import json
from pydantic import BaseModel


class JsonTest(BaseModel):
b_field: int
a_field: str

obj = JsonTest(b_field=1, a_field="one")

# this worked in pydantic v1 but raises a TypeError in v2
# print(obj.json(sort_keys=True)

print(obj.model_dump_json())
# {"b_field":1,"a_field":"one"}

# workaround for simple objects
print(json.dumps(obj.model_dump(), sort_keys=True))
# {"a_field": "one", "b_field": 1}

更多回答
优秀答案推荐

I'm not sure whether it is an elegant solution but you could leverage the fact that dictionaries (since python 3.7) preserve an order of elements:

我不确定这是否是一个优雅的解决方案,但您可以利用这样一个事实,即字典(从Python3.7开始)保留元素的顺序:


from typing import Any, Dict
from pydantic import BaseModel, model_serializer


class JsonTest(BaseModel):
b_field: int
c_field: int
a_field: str

@model_serializer(when_used='json')
def sort_model(self) -> Dict[str, Any]:
return dict(sorted(self.model_dump().items()))


obj = JsonTest(b_field=1, a_field="one", c_field=0)
print(obj.model_dump_json())
# {"a_field":"one","b_field":1,"c_field":0}


Hi!

嗨!


Try using the model_dump method and the sort_keys parameter of json.dumps to achieve sorting of keys in the JSON output in pydantic v2.

尝试使用json.dups的MODEL_DUMP方法和SORT_KEYS参数来实现对PYDINCTIONv2中的JSON输出中的键进行排序。


import json
from pydantic import BaseModel

class JsonTest(BaseModel):
b_field: int
a_field: str

obj = JsonTest(b_field=1, a_field="one")

# Use the model_dump method to get a dictionary and then sort the keys
sorted_json = json.dumps(obj.model_dump(), sort_keys=True)

print(sorted_json)
# {"a_field": "one", "b_field": 1}

This will produce a JSON striing with sorted keys. The model_dump method returns a dictionary representation of the Pydantic model, and then json.dumps is used with the sort_keys=True parameter to sort the keys alphabeticaly in the resulting JSON string.

这将生成一个带有排序键的JSON字符串。model_dump方法返回Pydantic模型的字典表示,然后使用json.dumps和sort_keys=True参数对结果JSON字符串中的键进行分类。


You can read more here: https://docs.pydantic.dev/latest/usage/serialization/

你可以在这里阅读更多内容:https://docs.pydantic.dev/latest/usage/serialization/


更多回答

yes, that's the workaround i posted i the original question. i was hoping there was a more robust solution that could handle the additional dtypes that pydantic can do docs.pydantic.dev/2.3/usage/serialization/#modelmodel_dump_json

是的,这就是我在原始问题中发布的解决方法。我希望有一种更健壮的解决方案,可以处理PYDINIC可以处理docs.pydantic.dev/2.3/usage/serialization/#modelmodel_dump_json的额外数据类型

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com