JSON 序列化一个类并使用 Python 更改属性大小写 [英] JSON serialize a class and change property casing with Python
问题描述
我想创建一个类的 JSON 表示并自动将属性名称从 snake_case
更改为 lowerCamelCase
,因为我想遵守 PEP8Python 和 JavaScript 命名约定(也许更重要的是,我要与之通信的后端使用 lowerCamelCase
).
我更喜欢使用标准的 json
模块,但我不反对使用另一个开源库(例如 jsonpickle
可能会解决我的问题?).
您只需要创建一个函数,将snake_case 键转换为camelCase.您可以使用 .split
、.lower
和 .title
轻松做到这一点.
导入json类硬件配置文件:def __init__(self, vm_size):self.vm_size = vm_sizeself.some_other_thing = 42self.a = 'a'def snake_to_camel(s):a = s.split('_')a[0] = a[0].lower()如果 len(a) >1:a[1:] = [u.title() for u in a[1:]]返回 ''.join(a)定义序列化(对象):返回 {snake_to_camel(k): v for k, v in obj.__dict__.items()}hp = HardwareProfile('大')打印(json.dumps(serialise(hp), indent=4, default=serialise))
输出
<代码>{"vmSize": "大",其他东西":42,一个":一个"}
你可以把serialise
放在lambda
中,但我认为把它写成一个合适的def
更具可读性代码>函数.
I'd like to create a JSON representation of a class and change the property names automatically from snake_case
to lowerCamelCase
, as I'd like to comply with PEP8 in Python and also the JavaScript naming conventions (and maybe even more importantly, the backend I'm communicating to uses lowerCamelCase
).
I prefer to use the standard json
module, but I have nothing against using another, open source library (e.g. jsonpickle
might solve my issue?).
>>> class HardwareProfile:
... def __init__(self, vm_size):
... self.vm_size = vm_size
>>> hp = HardwareProfile('Large')
>>> hp.vm_size
'Large'
### ### What I want ### ###
>>> magicjson.dumps(hp)
'{"vmSize": "Large"}'
### ### What I have so far... ### ###
>>> json.dumps(hp, default=lambda o: o.__dict__)
'{"vm_size": "Large"}'
You just need to create a function to transform the snake_case keys to camelCase. You can easily do that using .split
, .lower
, and .title
.
import json
class HardwareProfile:
def __init__(self, vm_size):
self.vm_size = vm_size
self.some_other_thing = 42
self.a = 'a'
def snake_to_camel(s):
a = s.split('_')
a[0] = a[0].lower()
if len(a) > 1:
a[1:] = [u.title() for u in a[1:]]
return ''.join(a)
def serialise(obj):
return {snake_to_camel(k): v for k, v in obj.__dict__.items()}
hp = HardwareProfile('Large')
print(json.dumps(serialise(hp), indent=4, default=serialise))
output
{
"vmSize": "Large",
"someOtherThing": 42,
"a": "a"
}
You could put serialise
in a lambda
, but I think it's more readable to write it as a proper def
function.
这篇关于JSON 序列化一个类并使用 Python 更改属性大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!