解析JSON对象时,保留字作为数据类中的属性名称 [英] Reserved word as an attribute name in a dataclass when parsing a JSON object

查看:336
本文介绍了解析JSON对象时,保留字作为数据类中的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ETL管道上工作时,我偶然发现了一个问题.我正在使用数据类dataclass来解析JSON对象. JSON对象的关键字之一是保留关键字.有没有解决的办法:

I stumbled upon a problem, when I was working on my ETL pipeline. I am using dataclasses dataclass to parse JSON objects. One of the keywords of the JSON object is a reserved keyword. Is there a way around this:

from dataclasses import dataclass
import jsons

out = {"yield": 0.21}

@dataclass
class PriceObj:
    asOfDate: str
    price: float
    yield: float

jsons.load(out, PriceObj)

这显然会失败,因为yield是保留的.查看数据类field的定义,似乎没有什么可以帮助您的.

This will obviously fail because yield is reserved. Looking at the dataclasses field definition, there doesn't seem to be anything in there that can help.

转到,允许定义JSON字段的名称,想知道dataclass中是否有这样的功能?

Go, allows one to define the name of the JSON field, wonder if there is such a feature in the dataclass?

推荐答案

您可以使用dataclasses_json lib从其

You can decode / encode using a different name with the dataclasses_json lib, from their docs:

from dataclasses import dataclass, field

from dataclasses_json import config, dataclass_json

@dataclass_json
@dataclass
class Person:
    given_name: str = field(metadata=config(field_name="overriddenGivenName"))

Person(given_name="Alice")  # Person('Alice')
Person.from_json('{"overriddenGivenName": "Alice"}')  # Person('Alice')
Person('Alice').to_json()  # {"overriddenGivenName": "Alice"}

这篇关于解析JSON对象时,保留字作为数据类中的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆