sirlark sirlark - 1 year ago 48
JSON Question

Ho do I specify how ActiveSupport::JSON.encode handles nested hash integer keys

I'm not sure if this is a bug, or if I'm missing an option to specify how to handle integer keys of nested hashes when converting to JSON using rails

. Example of the problem

$ rails console
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
Loading development environment (Rails

Frame number: 0/5
[1] pry(main)> ActiveSupport::JSON.encode({outer: {1 => "a"}})
=> "{\"outer\":{\"1\":\"a\"}}"

As you can see, the inner hash key
has been converted to a string. I know there are various options to specify how to handle unknown classes/type and ActiveRecord specific things (like allowing joins with
), but I would have thought that an integer as a 'native' type wouldn't require that sort of thing, and that nesting would be handled by default.


In JSON, the “keys” must always be strings.

=> a = { 1 => "1" }
#> {1=>"1"}
=> a.to_json
#> "{\"1\":\"1\"}"
=> JSON.parse(a.to_json)
#> {"1"=>"1"}