Forum: Ruby Convert String to hashes

Ecec81af7caddc8730eee285475df4da?d=identicon&s=25 ruby rails (rubyonrails)
on 2014-04-20 13:28
Hi,

I have a string object which is returned from the controller like below.

details = "{"name"=>"David", "age"=>"12", "emp_id"=>"E009", "exp"=>"10",
"company"=>"Starlink"}"

So the details.class would be String.
I need to convert it as Hash Json  so the output would be in below
format.

{
  "name":"David",
  "age":"12",
  "emp_id":"E009",
  "exp":"10",
  "company":"Starlink"
    }

How do I achieve it. Please help
4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (shevegen)
on 2014-04-20 17:20
I did not understand your question.

What is your string exactly?

Is it:


string = 'details = "{"name"=>"David", "age"=>"12", "emp_id"=>"E009",
"exp"=>"10", "company"=>"Starlink"}"'

?

Anyway, you need to parse that on your own and populate your hash.


string = 'details = "{"name"=>"David", "age"=>"12", "emp_id"=>"E009",
"exp"=>"10", "company"=>"Starlink"}"'
string = string[string.index('{')+1 .. -1] # chop off until first {
string[string.index('}')-1 .. -1] = '' # chop off until last }
hash = Hash[*string.scan(/\w+/)]

Now hash is this:

hash # => {"name"=>"David", "age"=>"12", "emp_id"=>"E009", "exp"=>"10",
"company"=>"Starlink"}


btw in your example, you used:

{
  "name":"David",
  "age":"12",
  "emp_id":"E009",
  "exp":"10",
  "company":"Starlink"
    }


And this is a syntax error. Are you sure you checked that the example
you try to achieve is valid ruby?
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2014-04-21 10:00
This is the simplest way to turn a String into JSON:

require 'json'
hash = JSON.parse string
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.