Search code examples
pythonpython-dataclasses

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?


Solution

  • 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"}