jkj2000 jkj2000 - 7 months ago 9
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
myvar['myval1']
I get back
'myval1'
, which isn't quite what I'm after. The answer's probably staring right at me but nothing's worked so far.

Answer

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

hash['myval1']
#=> "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:

eval(myvar)
#=> { "myval1"  => "value1", "mayval2" => "value2" }

eval(myvar)['myval1']
#=> "value1"

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