Home > Software design >  how to convert a JSON-String to multiple Structs in Julia
how to convert a JSON-String to multiple Structs in Julia

Time:09-16

I have the following JSON-String:

jsonString="""{
"struct1": {
    "arg1": 218650.27,
    "arg2": 90
},
"struct2": {
    "arg1": 346.4
}
}"""

I know already how to convert a JSON-String to a struct, but not a multiple struct like the JSON File above. Is there any Pkg that helps in this case, or I have to split the JSON file?

CodePudding user response:

You can parse JSON to get a dictionary of objects using JSON3:

julia> u = JSON3.read_json_str(jsonString)
JSON3.Object{Base.CodeUnits{UInt8, String}, Vector{UInt64}} with 2 entries:
  :struct1 => {…
  :struct2 => {…

julia> keys(u)
KeySet for a JSON3.Object{Base.CodeUnits{UInt8, String}, Vector{UInt64}} with 2 entries. Keys:
  :struct1
  :struct2

Than each element can be read as a separate Dict (here I cast it to Dict for readibility):

julia> Dict(u[:struct2])
Dict{Symbol, Any} with 1 entry:
  :arg1 => 346.4

julia> Dict(u[:struct1])
Dict{Symbol, Any} with 2 entries:
  :arg1 => 2.1865e5
  :arg2 => 90

Now suppose you have a dedicated Julia struct to fill-in with those values such as:

Base.@kwdef struct MyStruct
    arg1::Float64 = 0.0
    arg2::Int = 0
end

If you now want to store your JSON in such struct you can do:

julia> [MyStruct(;u[key]...) for key in keys(u)]
2-element Vector{MyStruct}:
 MyStruct(218650.27, 90)
 MyStruct(346.4, 0)
  • Related