Skip to content

Transform key in dict to attribute in dataclass #323

Answered by yukinarit
davetapley asked this question in Q&A
Discussion options

You must be logged in to vote

@davetapley

How about using dict?

from dataclasses import dataclass
from serde import serde
from serde.json import from_json, to_json

s = """
{
  "alert1/622": {
    "meta": {
      "sensor": {
        "name": "Battery Voltage"
      },
      "station": {
        "name": "Redrock Repeater "
      }
    }
  }
}
"""

@serde
@dataclass
class Entity:
    name: str

@serde
@dataclass
class Meta:
    sensor: Entity
    station: Entity

@serde
@dataclass
class Data:
    pass

@serde
@dataclass
class Sensor:
    meta: Meta | None
    data: Data | None

d = from_json(dict[str, Sensor], s)
print(d)
print(to_json(d))

Output

{'alert1/622': Sensor(meta=Meta(sensor=Entity(name='Battery Voltage'), stat…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@davetapley
Comment options

@yukinarit
Comment options

Answer selected by davetapley
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants