1

I have ugly string that looks like this:

"\"New\"=>\"0\""

Which will be the best way to converting it into hash object?

Mateusz Urbański
  • 7,352
  • 15
  • 68
  • 133

3 Answers3

3

Problem with "\"New\"=>\"0\"" is it does not look like a Hash. So first step should be to manipulate it to look like a Hash:

"{" + a + "}"
# => "{\"New\"=>\"0\"}"

Now once you have a hash looking string you can convert it into Hash like this:

eval "{" + a + "}"
# => {"New"=>"0"}

However there is still one issue, eval is not safe and inadvisable to use. So lets manipulate the string further to make it look json-like and use JSON.parse:

require `json`
JSON.parse ("{" + a + "}").gsub("=>",":")
# => {"New"=>"0"}
Community
  • 1
  • 1
shivam
  • 16,048
  • 3
  • 56
  • 71
2

How about JSON.parse(string.gsub("=>", ":"))

Niels Kristian
  • 8,661
  • 11
  • 59
  • 117
  • 1
    you need to manipulate string, else you'll get `JSON::ParserError: 757: unexpected token at '"New":"0"'` – shivam Jul 02 '15 at 06:55
2

You can use regex to pull out the key and value. Then create Hash directly

Hash[*"\"New\"=>\"0\"".scan(/".*?"/)]

Hard to nail down the best way if you can't tell us exactly the general format of those strings. You may not even need the regex. eg

Hash[*"\"New\"=>\"0\"".split('"').values_at(1,3)]

Also works for "\"Rocket\"=>\"=>\""

John La Rooy
  • 295,403
  • 53
  • 369
  • 502