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
?
Python introduced the dataclass in version 3.7 (PEP 557). The dataclass allows you to define classes with less code and more functionality out of the box. The following defines a regular Person class with two instance attributes name and age : class Person: def __init__(self, name, age): self.name = name self.age = age.
DataClass in Python DataClasses are like normal classes in Python, but they have some basic functions like instantiation, comparing, and printing the classes already implemented. Parameters: init: If true __init__() method will be generated. repr: If true __repr__() method will be generated.
A data class is a class typically containing mainly data, although there aren't really any restrictions. It is created using the new @dataclass decorator, as follows: from dataclasses import dataclass @dataclass class DataClassCard: rank: str suit: str.
The class keyword in Python is used to define classes. A class is a blueprint from which objects are created in Python. Classes bundle data and functionality together. Writing a class creates a new object type in your project.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With