JuliaIO / JSON.jl

JSON parsing and printing
Other
311 stars 100 forks source link

Dict written as a String #328

Open ZacharieALES opened 3 years ago

ZacharieALES commented 3 years ago

When I save into a json file a Dict which contains a Dict as a key, the key is replaced by a string.

Here is an example: d = Dict{Dict{String, Int}, Int}(Dict("v1" => 1) => 2)

I save variable d using

julia> open("test.json", "w") do f
         JSON.print(f, d, 4)
       end

The problem is that I get the following json file:

{
    "Dict(\"v1\" => 1)": 2
}

and when I read the file, due to the quotation marks, Dict(\"v1\" => 1) is considered to be a String rather than a Dict{String, Int}:

julia> sData = join(readlines("test.json"))
julia> dExtracted = JSON.parse(sData)
Dict{String,Any} with 1 entry:
  "Dict(\"v1\" => 1)" => 2

Can I write and read in json a Dict which has a Dict as keys?

ZacharieALES commented 3 years ago

After some reading, I found that the name of an object in json is necessarily a string.

I replaced the type Dict{Dict{String, Int} by Vector{Vector{Any}} which is not completely satisfactory but works.

KristofferC commented 3 years ago

Personally I think JSON.jl should error on such keys and not just naively stringify them.

ZacharieALES commented 3 years ago

That would have saved me some debugging and reading ^^'.