How to Convert Julia Dictionary Keys from Strings to Integer

Viewed 1368

I want to convert Julia Dictionary Keys that are Strings to Integers

JSON3 converts the keys of my Dictionary into Strings. My understanding is that JSON keys are only strings.

using JSON3

a1 = Dict(1 => "one", 2 => "two", 3  => "three")

a1_json =  JSON3.write(a1)
  "{\"2\":\"two\",\"3\":\"three\",\"1\":\"one\"}"

a2 = JSON3.read(json,Dict{Int64,String})
  ERROR: MethodError: no method matching Int64(::String)

Is there any way to keep the keys in Int?

1 Answers

from JSON3.jl readme:

Declaring my type is JSON3.ObjectType() means it should map to a JSON object of >unordered key-value pairs, where keys are Symbol or String, and values are any other type (or Any).

So, in the parse step, you are gonna get symbols if you use numbers as keys. with that said, you can use this code to recover the original dict:

Dict(parse(Int,string(k))=>v  for (k,v) in pairs(a2))
Related