Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSON object into a python dataclass without third party library?

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)
like image 917
sji gshan Avatar asked Nov 16 '25 03:11

sji gshan


1 Answers

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)
like image 160
Don Avatar answered Nov 18 '25 18:11

Don



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!