sji*_*han 7 python json python-dataclasses
我想解析 json 并将其保存在数据类中以模拟 DTO。目前,我必须手动将所有 json 字段传递给数据类。我想知道有没有一种方法可以通过添加 json 解析的字典来做到这一点。“dejlog”到数据类,所有字段都会自动填充。
from dataclasses import dataclass, asdict
@dataclass
class Dejlog(Dataclass):
PK: str
SK: str
eventtype: str
result: str
type: str
status: str
def lambda_handler(event, context):
try:
dejlog = json.loads(event['body'])
x = Dejlog(dejlog['PK'])
print(x)
print(x.PK)
Run Code Online (Sandbox Code Playgroud)
小智 7
json正如其他评论中提到的,您可以像这样使用内置库:
from dataclasses import dataclass
import json
json_data_str = """
{
"PK" : "Foo",
"SK" : "Bar",
"eventtype" : "blah",
"result" : "something",
"type" : "badger",
"status" : "active"
}
"""
@dataclass
class Dejlog:
PK: str
SK: str
eventtype: str
result: str
type: str
status: str
json_obj = json.loads(json_data_str)
dejlogInstance = Dejlog(**json_obj)
print(dejlogInstance)
Run Code Online (Sandbox Code Playgroud)
小智 7
只要 json 对象中没有任何意外的键,解包就可以进行,否则您将收到 TypeError。另一种方法是使用类方法来创建数据类的实例。基于前面的示例:
json_data_str = """
{
"PK" : "Foo",
"SK" : "Bar",
"eventtype" : "blah",
"result" : "something",
"type" : "badger",
"status" : "active",
"unexpected": "I did not expect this"
}
"""
@dataclass
class Dejlog:
PK: str
SK: str
eventtype: str
result: str
type: str
status: str
@classmethod
def from_dict(cls, data):
return cls(
PK = data.get('PK'),
SK = data.get('SK'),
eventtype = data.get('eventtype'),
result=data.get('result'),
type=data.get('type'),
status=data.get('status')
)
json_obj = json.loads(json_data_str)
dejlogInstance = Dejlog.from_dict(json_obj)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12855 次 |
| 最近记录: |