如何将JSON对象解析为Python数据类而不使用第三方库?

6

我希望能够解析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)

import json 包含了你所需的所有函数。 - user18626799
将 JSON 加载到字典中,然后可迭代地拆包并转换为数据类实例。 - rv.kvetch
如果 dejlog 包含了期望的键,你需要的是 x = Dejlog(**dejlog) - Serge Ballesta
@SergeBallesta 谢谢,但是如果JSON中添加了新的(意外的)键,则解包将失败。有什么办法可以克服它?此外,如果JSON中的某些字段包含列表或对象,并且在数据类中我已经提到了str。如何处理它们? - sji gshan
2个回答

5

如其他评论所提到的,您可以使用内置的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)

5

只要在json对象中没有任何意外的键,解包就可以正常工作,否则会出现TypeError。另一种选择是使用classmethod来创建数据类的实例。基于之前的示例构建:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接