I have a relatively complex and nested JSON object (representing a patent application) which I would like to deserialize into a struct.
However, I would like to “de-nest” the structure somewhat and between the different options provided by the awesome StructTypes.jl, such as wrapper types or mapping field names, I am still unsure what a feasible solution looks like.
Here’s a simplified example of what the JSON look like:
Thanks for the quick reply. As I understand it, the mutable struct and the inner constructor is StructTypes.jl’s way of rubustly dealing with e.g. missing fields in the JSON (see the docs).
I guess doing the parsing and dealing with exceptions manually would be a possibility, but I would rather use the StructTypes machinery as the actual json is much more complex and the manual route would probably be more error prone and less efficient.
I see. Sorry, I’m not experienced with StructTypes.jl. I wonder though if that doesnt cause a lot of problems because you’re splitting up parsing and validation…
I see, thanks. Creating all the intermediate structs was my first approach and JSON3.@generatetypes actually turned that from a very tedious task into a breeze. But parsing directly into the final structure would have been more elegant.
Strapping.jl looks nice but in this case neither the input JSON nor the targeted output struct are really flat/tabular - it’s just that the JSON is more nested than necessary for the target struct so I would like to skip some of the nesting levels while keeping others.
Yeah, Strapping.jl works well when you need to completely unnest, but it’s certainly tricky when you only want to selectively unnest. I dealt with this once in a project, but not quite as complex as your case; in my case, I just did JSON3.read(json), which returns a JSON3.Object. In StructTypes, we have a StructTypes.constructfrom(T, x) method that allows constructing T from x, where x is some kind of AbstractDict (like JSON3.Object).
Then you just define your own constructing machinery that does something like:
function unnest(json)
x = JSON3.read(json)
# pull the pieces out of x that are needed
end