您如何处理映射骆驼json到snake_case python dataclass字段名称?

发布于 2025-01-25 15:26:23 字数 556 浏览 3 评论 0 原文

我正在使用Python与Web API进行交互,其中JSON响应中的键在骆驼中。我的Python模型是Dataclasses,谁的字段名称为Snake_case。当我从JSON转换为Model和Vise-Versa时,名称显然不匹配。

作为参考,我正在使用Asdict函数将我的模型转换为JSON。

def to_json(self):
  return asdict(
    self, 
    dict_factory=lambda _fields: {
      key: value for (key, value) in _fields if value is not None
    }
  )

从JSON转换为模型的代码更为复杂,但也依赖于映射到JSON键的字段名称。这两种转换都足够通用,可以与我的所有模型一起使用,而无需为每个模型创建转换器(30左右)。

在这种情况下,是否常用于我的模型字段名称(即使它不符合标准命名实践)是常见的做法吗?

我无法修改API,无论好坏,关键名称总是在骆驼中。

I'm using Python to interact with a web api, where the keys in the json responses are in camelCase. My python models are dataclasses, who's field names are snake_case. When I convert from json to model and vise-versa, the names obviously do not match up.

For reference, I'm using the asdict function to convert my models to json.

def to_json(self):
  return asdict(
    self, 
    dict_factory=lambda _fields: {
      key: value for (key, value) in _fields if value is not None
    }
  )

The code that converts from json to model is slightly more complicated, but also relies on the field names for mapping to the json keys. Both of the conversions are generic enough that it works with all my models, without having to create converters for each individual model (30 or so).

In this case, is it common practice to use cameCase for my model field names (even though it doesn't conform to standard naming practice)?

I cannot modify the api, for better or worse the key names will always be in camelCase.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬 2025-02-01 15:26:23

一个选项可能是使用 dataclass-wizard 库,该库支持 camelcase的自动映射(或 pascalcase 脊髓案例)to snake_case ,这是Python中的约定。它最终还应该比棉花糖之类的速度快一点,尽管老实说,我自己没有自己测试过。

一个简化的示例,取自文档:

from __future__ import annotations
from dataclasses import dataclass, field
from dataclass_wizard import JSONWizard

@dataclass
class MyClass(JSONWizard):
    my_str: str | None
    is_active_tuple: tuple[bool, ...]
    list_of_int: list[int] = field(default_factory=list)

string = """
{
  "my_str": 20,
  "ListOfInt": ["1", "2", 3],
  "isActiveTuple": ["true", false, 1]
}
"""

instance = MyClass.from_json(string)
print(f'{instance!r}')
# MyClass(my_str='20', is_active_tuple=(True, False, True), list_of_int=[1, 2, 3])
print(instance.to_json())
# '{"myStr": "20", "isActiveTuple": [true, false, true], "listOfInt": [1, 2, 3]}'
assert instance == MyClass.from_dict(instance.to_dict())  # True

dataclass-wizard 可以使用 pip

$ pip install dataclass-wizard

One option could be to use the dataclass-wizard library, which supports automatic mapping of camelCase (or PascalCase or spinal-case) to snake_case, which is convention in Python. It should also end up being a little faster than something like marshmallow, though honestly I haven't tested this out myself.

A simplified example, taken from the docs:

from __future__ import annotations
from dataclasses import dataclass, field
from dataclass_wizard import JSONWizard

@dataclass
class MyClass(JSONWizard):
    my_str: str | None
    is_active_tuple: tuple[bool, ...]
    list_of_int: list[int] = field(default_factory=list)

string = """
{
  "my_str": 20,
  "ListOfInt": ["1", "2", 3],
  "isActiveTuple": ["true", false, 1]
}
"""

instance = MyClass.from_json(string)
print(f'{instance!r}')
# MyClass(my_str='20', is_active_tuple=(True, False, True), list_of_int=[1, 2, 3])
print(instance.to_json())
# '{"myStr": "20", "isActiveTuple": [true, false, true], "listOfInt": [1, 2, 3]}'
assert instance == MyClass.from_dict(instance.to_dict())  # True

The dataclass-wizard library can be installed with pip:

$ pip install dataclass-wizard
暗地喜欢 2025-02-01 15:26:23

在这种情况下,使用骆驼作为我的模型字段名称是否常见的做法(即使它不符合标准命名实践)?

这不是一个普遍的做法,但这全都与惯例有关。只要您的代码按其自身的标准保持一致,这也不是问题。

但是,通过在 @dataclass_json()注释中使用参数 Letter_case ,可以为这种情况提供一个简单的解决方案。让我们以 @rv.kvetch示例

@dataclass_json(letter_case=LetterCase.CAMEL)  # now all fields are encoded/decoded from camelCase
@dataclass
class MyClass():
    my_str: str | None
    is_active_tuple: tuple[bool, ...]
    list_of_int: list[int] = field(default_factory=list)

示例:

In this case, is it common practice to use camelCase for my model field names (even though it doesn't conform to standard naming practice)?

It is not a common practice, but this is all about convention. As long as your code is consistent by its own standards this shouldn't be a problem.

However, there is a simple solution for this case by using the parameter letter_case in the @dataclass_json() annotation. Let's take @rv.kvetch example:

@dataclass_json(letter_case=LetterCase.CAMEL)  # now all fields are encoded/decoded from camelCase
@dataclass
class MyClass():
    my_str: str | None
    is_active_tuple: tuple[bool, ...]
    list_of_int: list[int] = field(default_factory=list)

Reference: https://pypi.org/project/dataclasses-json/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文