Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash with integer keys changed to string keys

Tags:

json

ruby

hash

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

like image 343
DanMatlin Avatar asked Aug 20 '14 12:08

DanMatlin


People also ask

Can a Ruby Hash key be an integer?

Integers are objects in Ruby, so are Hashes for that matter so you could use Hashes as keys.

Can a Hash key be a number?

Hash key may refer to: Number sign, also known as the number, pound or hash key, a key on a telephone keypad.

How do you rename a Hash key in Ruby?

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.

How do you make Hash Hash in Ruby?

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.


1 Answers

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
like image 197
Martin Avatar answered Nov 15 '22 05:11

Martin