I need to process multiple messages in JSON format. Each message has its own nested structure. I would like to create a Python SDK to process these messages. My idea is to map each JSON structure into a set of nested Python classes. Currently, I'm doing it manually. But it is a tedious task.
Please find an example JSON message below:
{
"GlobalGnbId": {
"PlmnIdentity": {
"Data": [
19,
241,
132
]
},
"GnbId": {
"Value": 1,
"Length": 22
}
},
"OptionalGnbDuId": 1
}
Please find below my own handcrafted set of Python classes to work with this JSON message:
class PlmnIdentity(BaseModel):
"""Class for PLMN identity"""
Data: list[int]
class GnbId(BaseModel):
"""Class for gNodeB ID"""
Value: int
Length: int
class GlobalGnbId(BaseModel):
"""Class for global gNodeB ID"""
PlmnIdentity: PlmnIdentity
GnbId: GnbId
class NodeId(BaseModel):
"""Class for node ID"""
GlobalGnbId: GlobalGnbId
OptionalGnbDuId: int
Finally, please find below a full minimal example:
from pydantic import BaseModel, TypeAdapter
import json
class PlmnIdentity(BaseModel):
"""Class for PLMN identity"""
Data: list[int]
class GnbId(BaseModel):
"""Class for gNodeB ID"""
Value: int
Length: int
class GlobalGnbId(BaseModel):
"""Class for global gNodeB ID"""
PlmnIdentity: PlmnIdentity
GnbId: GnbId
class NodeId(BaseModel):
"""Class for node ID"""
GlobalGnbId: GlobalGnbId
OptionalGnbDuId: int
node_id_str = \
"""
{
"GlobalGnbId": {
"PlmnIdentity": {
"Data": [
19,
241,
132
]
},
"GnbId": {
"Value": 1,
"Length": 22
}
},
"OptionalGnbDuId": 1
}
"""
# NodeId as class
node_id_class = TypeAdapter(NodeId).validate_json(node_id_str)
print(node_id_class)
print(node_id_class.GlobalGnbId)
print(node_id_class.GlobalGnbId.PlmnIdentity)
print(node_id_class.GlobalGnbId.PlmnIdentity.Data)
print(node_id_class.GlobalGnbId.GnbId)
print(node_id_class.GlobalGnbId.GnbId.Value)
print(node_id_class.GlobalGnbId.GnbId.Length)
print(node_id_class.OptionalGnbDuId)
# NodeId as dictionary
node_id_dict = node_id_class.model_dump()
print(node_id_dict)
My question is there an automatic or semi-automatic way to map a nested JSON message to a set of Python classes?
NodeId.GlobalGnbId.GnbIdinstead of a nested dictionary notationdict['NodeId']['GlobalGnbId']['GnbId'].SimpleNamespacefrom the built-in types library to wrap thedictobject and then access fields using "dot" notation. See a basic example here. You can couple this with JSON schema validation to validate the incomingJSON. See a basic example here. The schema can be defined in code (like the example) or loaded from file.v1major release, will be approximately 2x faster than Pydantic. Just sharing for awareness. Thanks!