0


I have a string that looks like this: {"whatever-field"=>"gghyduudud"}
I'd like to parse it so that it becomes a hash.

Please help.

Thanks!

Linuxios
  • 34,849
  • 13
  • 91
  • 116
Svarog
  • 2,188
  • 15
  • 21

2 Answers2

1

You can use eval, but only if the data source is absolutely reliable:

>> eval('{"whatever-field"=>"gghyduudud"}')
=> {"whatever-field"=>"gghyduudud"} 
tokland
  • 66,169
  • 13
  • 144
  • 170
  • That could be very risky, although it is the only way if it contains other data types. Maybe you can validate the data on a regex first? – Linuxios Dec 19 '11 at 16:12
  • @Linux_iOS.rb.cpp.c.lisp.m.sh: That's why I said "aboslute reliable". If it comes from a user is no good, if you are sending it your own string it's ok. – tokland Dec 19 '11 at 16:31
  • Yes. That is why all of the computer literature warns against ever using explicit eval. It seems that `eval` is considered bad practice. Here it makes a lot of sense though. Just thought it was worth mentioning. Of course, if the data must come from outside, you could wrap this in its own thread with a safe level of 4. But that seems a bit cumbersome for just parsing strings. – Linuxios Dec 19 '11 at 17:01
0

Here is a solution:

dictionary=Hash[*(dict_str[1..dict_str.length-2].split("=>").map {|strval| strval[1..strval.length-2]})]

That will work as long as you want the keys and values as strings. Its a bit long, but it worked for me.

Linuxios
  • 34,849
  • 13
  • 91
  • 116