如何在没有第三方库的情况下将JSON对象解析到python数据级中?

发布于 2025-01-24 05:52:44 字数 483 浏览 0 评论 0原文

我想解析JSON并将其保存在数据级别中以模拟DTO。 目前,我要手动将所有JSON字段传递到Dataclass。 我想知道,只要添加JSON解析的dict ie,我就可以做到这一点。 “ 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)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

趁微风不噪 2025-01-31 05:52:44

如其他注释中所述,您可以使用内置json lib如下:

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)

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)
江心雾 2025-01-31 05:52:44

只要您在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)

Unpacking works as long as you don't have any unexpected keys in the json object, otherwise you'll get a TypeError. An alternative is to use a classmethod to create instances of the dataclass. Building on the earlier example:

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)
感情旳空白 2025-01-31 05:52:44

您可以使用hook_object参数加载JSON到您的数据级对象:

import json
from dataclasses import dataclass


@dataclass
class Dejlog:
    PK: str
    SK: str
    eventtype: str
    result: str
    type: str
    status: str


my_obj = json.loads(
    open('/path/to/file', 'r').read(),
    object_hook=lambda args: Dejlog(**args)
)

You can load json to your dataclass object using hook_object param like this:

import json
from dataclasses import dataclass


@dataclass
class Dejlog:
    PK: str
    SK: str
    eventtype: str
    result: str
    type: str
    status: str


my_obj = json.loads(
    open('/path/to/file', 'r').read(),
    object_hook=lambda args: Dejlog(**args)
)
月棠 2025-01-31 05:52:44

这是一个简单的分类,可以处理丢失或额外的键。以较早的答案为基础:

import dataclasses
import json

json_data_str = """
{
   "PK" : "Foo",
   "SK" : "Bar",
   "eventtype" : "blah",
   "result" : "something",
   "type" : "badger",
   "status" : "active",
   "unexpected": "I did not expect this"
}
"""

@dataclasses.dataclass
class Dejlog:
    PK: str
    SK: str
    eventtype: str
    result: str
    type: str
    status: str

    @classmethod
    def from_dict(cls, data):
        return cls(
            *[data.get(fld.name)
              for fld in dataclasses.fields(Dejlog)]
        )

json_obj = json.loads(json_data_str)
dejlogInstance = Dejlog.from_dict(json_obj)

Here is a simple classmethod that handles missing or extra keys. Building on an earlier answer:

import dataclasses
import json

json_data_str = """
{
   "PK" : "Foo",
   "SK" : "Bar",
   "eventtype" : "blah",
   "result" : "something",
   "type" : "badger",
   "status" : "active",
   "unexpected": "I did not expect this"
}
"""

@dataclasses.dataclass
class Dejlog:
    PK: str
    SK: str
    eventtype: str
    result: str
    type: str
    status: str

    @classmethod
    def from_dict(cls, data):
        return cls(
            *[data.get(fld.name)
              for fld in dataclasses.fields(Dejlog)]
        )

json_obj = json.loads(json_data_str)
dejlogInstance = Dejlog.from_dict(json_obj)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文