JSON3: create json using Dict() with integer keys

I have found that when the following is run, JSON’s converts int dictionary keys to strings.

julia> using JSON3
julia> a1 = Dict(1 => "one", 2 => "two", 3  => "three");
julia> json =  JSON3.write(a1)
"{\"2\":\"two\",\"3\":\"three\",\"1\":\"one\"}"
julia> a2 = JSON3.read(json,Dict{Int64,String})
ERROR: MethodError: no method matching Int64(::String)

Is there any way to preserve the key as an int?

AFAIK JSON keys are strings, no other types are allowed. You could parse to Int after reading.

2 Likes

@Tamas_Papp Thank you so much for your help.

Could you please provide a short example of parsing a Julia Dictionary from string to int? In the case the dictionary contains large amount of keys is this an efficient way to do it?

Continuing your example, something like

a2 = JSON3.read(json)
function keys_to_int(dict)
    Dict([parse(Int, string(key)) => val for (key, val) in pairs(dict)])
end
keys_to_int(a2)

should work.