1

I have ugly string that looks like this:

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

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

5
  • 3
    JSON.parse "{#{you_ugly_string.gsub('=>',':')}}" Commented Jul 2, 2015 at 6:49
  • It not works: JSON::ParserError: 757: unexpected token at '"New":"0"' Commented Jul 2, 2015 at 6:53
  • 1
    I tried and it works for me. Probably you are ignoring { and } in the string Commented Jul 2, 2015 at 6:59
  • 2
    This looks like the result of a Hash#inspect. Instead of trying to parse this string into a proper data structure, you should instead try to use the original hash and don't convert it into a string first. This data has no business being in a string there and you should save you the hassle of trying to extract it there.. Commented Jul 2, 2015 at 7:05
  • Please show the hash you desire. Commented Jul 2, 2015 at 7:22

3 Answers 3

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"}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

you need to manipulate string, else you'll get JSON::ParserError: 757: unexpected token at '"New":"0"'
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\"=>\"=>\""

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.