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. The keys are now string literals.
I get it that JSON doesnt support integer keys but I came upon this method which basically parses the hash so that it has symbol keys.
JSON.parse(hash, {:symbolize_names => true})
Is there a similar function for obtaining back 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 which is supposed to have integer keys. There are multiple such levels of nesting
Integers are objects in Ruby, so are Hashes for that matter so you could use Hashes as keys.
Hash key may refer to: Number sign, also known as the number, pound or hash key, a key on a telephone keypad.
This is a pretty neat snippet of Ruby that I found to rename a key in a Ruby hash. The #delete method on a hash will return the value of the key provided while removing the item from the hash. The resulting hash gets a new key assigned to the old key's value.
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
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 key & value from the initial hash (json_hash
), call to_i on them and get them in a new hash (integer_hash
).
Even nesting is not blocking. You could 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's a hash, let's call it again
else
new_value = v.to_i #it's a integer, let's convert
end
[k.to_i, new_value]
end
Hash[keys_values]
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With