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)
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.
Go, allows one to define the name of the JSON field, wonder if there is such a feature in the dataclass
?
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"}