Last active
November 1, 2022 08:02
-
-
Save hxer/8119b017d9492c72a6d6978e58a0b71e to your computer and use it in GitHub Desktop.
复杂dict对象转换dataclass对象
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from typing import Dict | |
from dataclasses import ( | |
asdict, dataclass, field, fields, is_dataclass | |
) | |
# 对于一些嵌套的数据类,需要深度遍历 | |
class EnhancedJSONEncoder(json.JSONEncoder): | |
def default(self, o): | |
if is_dataclass(o): | |
return asdict(o) | |
return super().default(o) | |
def dicts_to_dataclasses(instance): | |
"""将所有的数据类属性都转化到数据类中""" | |
cls = type(instance) | |
for f in fields(cls): | |
if not is_dataclass(f.type): | |
continue | |
value = getattr(instance, f.name) | |
if not isinstance(value, dict): | |
continue | |
new_value = f.type(**value) | |
setattr(instance, f.name, new_value) | |
@dataclass | |
class Base: | |
def __post_init__(self): | |
dicts_to_dataclasses(self) | |
def as_dict(self): | |
return asdict(self) | |
def as_json(self): | |
return json.dumps(self, cls=EnhancedJSONEncoder) | |
if __name__ == "__main__": | |
@dataclass | |
class Download(Base): | |
url: str | |
expire_time: int | |
headers: Dict = field(default_factory=dict) | |
download = { | |
'url': 'http://example.com', | |
'expire_time': 1, | |
'headers': { | |
'Content-Type': 'application/json' | |
} | |
} | |
d = Download(**download) | |
print(d.as_dict()) | |
print(d.as_json()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment