jkj2000 jkj2000 - 2 years ago 60
Ruby Question

How to convert this 'hash-like' string to a key value pair

I'm using Ruby 2.2 and have a string that looks like this:

myvar = '{"myval1"=>"value1","mayval2"=>"value2"}'

How can I get this into a key-value pair and/or hash of some sort? When I do
I get back
, which isn't quite what I'm after. The answer's probably staring right at me but nothing's worked so far.

Answer Source

You can change that string to valid JSON easily and use JSON.parse then:

require 'JSON'
myvar = '{"myval1"=>"value1","mayval2"=>"value2"}'

hash = JSON.parse(myvar.gsub(/=>/, ': '))
#=> { "myval1"  => "value1", "mayval2" => "value2" }

#=> "value1"

Unfortunately this will not work (as ndn pointed out) when a string in the hash include => itself.

Another option that is highly insecure might be to use eval:

#=> { "myval1"  => "value1", "mayval2" => "value2" }

#=> "value1"

Please do not consider using eval when you received the string from an external source, because all kind of dangerous things will happen.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download