msgspec
msgspec copied to clipboard
[Question] How to decode deeply nested part of json using msgspec
Question
What is the correct way to decode part of json file?
Is there a way to do this without defining class Stuct for every level?
Also how to handle when the keys have a .
like test.name
?
For example,
{
"test.name" : [
...
]
}
For the second question, you can use the name
argument in the field
function.
Like this:
class Something(Struct):
test_name: str = field(name="test.name")
@giridhart
You may want to have a look at Renaming Fileds. And in particular at "On the struct definition" part, which states that rename
parameter can be:
- A mapping from field names to the renamed names...
- A callable (signature
rename(name: str) -> Optional[str])
...
So if the builtin types are sufficient - the root Struct
like this should work:
class Root(msgspec.Struct, rename=lambda name: name.replace('_', '.')):
...
Yes, now I remember reading about renaming fields, I should read few times to cement my memory. Thank you.