msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

[Question] How to decode deeply nested part of json using msgspec

Open giridhart opened this issue 1 year ago • 3 comments

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" : [
...
]
}

giridhart avatar Nov 07 '23 10:11 giridhart

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")

FHU-yezi avatar Nov 07 '23 13:11 FHU-yezi

@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('_', '.')):
    ...

wikiped avatar Nov 07 '23 15:11 wikiped

Yes, now I remember reading about renaming fields, I should read few times to cement my memory. Thank you.

giridhart avatar Nov 07 '23 15:11 giridhart