Convert String to hashes

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

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?

This is the simplest way to turn a String into JSON:

require ‘json’
hash = JSON.parse string