Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataclass object property alias

I'm doing a project to learn more about working with Python dataclasses. Specifically, I'm trying to represent an API response as a dataclass object. However, I'm running into an issue due to how the API response is structured.

Here is an example response from the API:

{
    "@identifier": "example",
    "@name": "John Doe",
}

Some of the fields have special characters in their names. This means I cannot map the attributes of my dataclass directly, since special characters such as @ are not allowed in property names (SyntaxError).

Is there a way to define an alias for my dataclass properties, such that I can map the API response directly to the dataclass object? Or is it necessary to clean the response first?

like image 771
thijsfranck Avatar asked Jun 10 '26 01:06

thijsfranck


1 Answers

There is dataclasses-json, which allows you to alias attributes:

from dataclasses import dataclass, field
from dataclasses_json import config, dataclass_json


@dataclass_json
@dataclass
class Person:
    magic_name: str = field(metadata=config(field_name="@name"))
    magic_id: str = field(metadata=config(field_name="@identifier"))


p = Person.from_json('{"@name": "John Doe", "@identifier": "example"}')
print(p.magic_name)
print(p.to_json())

Out:

John Doe
{"@name": "John Doe", "@identifier": "example"}
like image 189
Maurice Meyer Avatar answered Jun 12 '26 14:06

Maurice Meyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!