Transform key in dict to attribute in dataclass #323
Answered
by
yukinarit
davetapley
asked this question in
Q&A
-
I'm getting JSON from an API which looks like this: {
"alert1/622": {
"meta": {
"sensor": {
"name": "Battery Voltage"
},
"station": {
"name": "Redrock Repeater "
},
}
} And I'd like to parse in to: @serde
@dataclass
class Sensor:
id: str
meta: Meta | None
data: Data | None Is there a way to transform the |
Beta Was this translation helpful? Give feedback.
Answered by
yukinarit
Mar 2, 2023
Replies: 2 comments 2 replies
-
How about using 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
|
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
davetapley
-
Or if you have only 1 pair of data and using @serde
@dataclass
class Entity:
name: str
@serde
@dataclass
class Meta:
sensor: Entity
station: Entity
@serde
@dataclass
class Data:
pass
@serde
@dataclass
class SensorData:
meta: Meta | None
data: Data | None
@serde
@dataclass
class Sensor:
sensor_id: SensorData = field(rename="alert1/622")
d = from_json(Sensor, s)
print(d)
print(to_json(d)) Output
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@davetapley
How about using
dict
?Output