我正在使用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.
发布评论
评论(2)
一个选项可能是使用 dataclass-wizard 库,该库支持 camelcase的自动映射(或 pascalcase 或脊髓案例)to snake_case ,这是Python中的约定。它最终还应该比
棉花糖
之类的速度快一点,尽管老实说,我自己没有自己测试过。一个简化的示例,取自文档:
dataclass-wizard 可以使用
pip
: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:
The dataclass-wizard library can be installed with
pip
:这不是一个普遍的做法,但这全都与惯例有关。只要您的代码按其自身的标准保持一致,这也不是问题。
但是,通过在
@dataclass_json()
注释中使用参数Letter_case
,可以为这种情况提供一个简单的解决方案。让我们以 @rv.kvetch示例示例:
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:Reference: https://pypi.org/project/dataclasses-json/