sirlark sirlark - 6 months ago 13
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

ActiveSupport::JSON.encode
. 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 3.2.22.1)

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


As you can see, the inner hash key
1
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
:include
), 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.

Answer

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"}
Comments