Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reserved word as an attribute name in a dataclass when parsing a JSON object

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?

like image 825
Naz Avatar asked Feb 05 '20 11:02

Naz


People also ask

What is@ dataclass in python?

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.

How does dataclass work in python?

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.

What is a dataclass?

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.

Is class A reserved keyword in Python?

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.


Video Answer


1 Answers

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"}
like image 185
Naz Avatar answered Oct 18 '22 15:10

Naz