Praveenkumar
Praveenkumar

Reputation: 981

How can I parse a String(not a json object) which is in jsonArray format in rails?

This is my value String form of JSON array(Not a JSON Object)

value= "[{\"a\":\"test a\"},{\"b\":\"test b updated\"}]"

when I tried to convert it to JSON using

value=value.to_json
#value= "\"[{\\\"a\\\":\\\"test a\\\"},{\\\"b\\\":\\\"test b updated\\\"}]\""

but I want my value like this

{"a":"test a","b":"test b updated"}

Any Suggestion ?

Upvotes: 1

Views: 35

Answers (2)

Jordan Running
Jordan Running

Reputation: 106077

First you need to turn the JSON string into a Ruby value:

arr = JSON.parse(value)
# => [ { "a" => "test a" },
#      { "b" => "test b updated" } ]

This will return a Ruby array whose items are hashes.

Next you need to merge the hashes into a single hash:

combined_hash = arr.reduce({}, &:merge)
# => { "a" => "test a",
#      "b" => "test b updated" }

Finally, turn the hash back into JSON:

puts combined_hash.to_json
# => {"a":"test a","b":"test b updated"}

All together:

arr = JSON.parse(value)
combined_hash = arr.reduce({}, &:merge)
puts combined_hash.to_json
# => {"a":"test a","b":"test b updated"}

You can see it in action here: http://ideone.com/l5BAiw

Upvotes: 1

Pramod S. Nikam
Pramod S. Nikam

Reputation: 4549

You need to use something like below:

json = JSON.parse(value).to_s

to_s is additionally added to convert it to string.

Upvotes: 0

Related Questions