Ruby Hash with whole keys changed to string keys

I create a hash in ruby ​​with integer keys and send it as a JSON response. This JSON is then parsed, and the hash is converted back to ruby. Keys are now string literals.

I get that JSON does not support whole keys, but I came across this method, which basically parses the hash so that it has character keys.

JSON.parse(hash, {:symbolize_names => true}) 

Is there a similar function to return the original integer keys

 a = {1 => 2} a.keys => [1] b = JSON.parse(JSON.generate(a)) b.keys => ["1"] 

My hash is very complicated. The value itself is a hash that must have integer keys. There are several levels of nesting.

+5
source share
1 answer

Nothing in JSON as far as I know, but conversion is easy:

 json_hash = {"1" => "2" } integer_hash = Hash[json_hash.map{|k,v|[ k.to_i, v.to_i ]}] => {1 => 2} 

So, we take all the key and value from the initial hash ( json_hash ), call to_i on them and get them into a new hash ( integer_hash ).

Even nesting does not block. You can do this in a method:

 def to_integer_keys(hash) keys_values = hash.map do |k,v| if(v.kind_of? Hash) new_value = to_integer_keys(v) #it a hash, let call it again else new_value = v.to_i #it a integer, let convert end [k.to_i, new_value] end Hash[keys_values] end 
+7
source

Source: https://habr.com/ru/post/1200748/


All Articles