如何在没有第三方库的情况下将JSON对象解析到python数据级中?
我想解析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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如其他注释中所述,您可以使用内置
json
lib如下:As mentioned in other comments you can use the in-built
json
lib as so:只要您在JSON对象中没有任何意外键,解开包装工作,否则您将获得TypeError。一种替代方法是使用ClassMethod创建数据级别的实例。建立在较早的示例上:
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:
您可以使用
hook_object
参数加载JSON到您的数据级对象:You can load json to your dataclass object using
hook_object
param like this:这是一个简单的分类,可以处理丢失或额外的键。以较早的答案为基础:
Here is a simple classmethod that handles missing or extra keys. Building on an earlier answer: