I want to parse json and save it in dataclasses to emulate DTO. Currently, I ahve to manually pass all the json fields to dataclass. I wanted to know is there a way I can do it by just adding the json parsed dict ie. "dejlog" to dataclass and all the fields are populated automactically.
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)
As mentioned in other comments you can use the in-built json
lib as so:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.