Forum: Ruby convert json string to hash and retrieve hash items values in ruby

Ecec81af7caddc8730eee285475df4da?d=identicon&s=25 ruby rails (rubyonrails)
on 2014-05-08 17:52
Hi,

I have a string object which is basically in a json format and while
trying to print it shows in console as


    item =
     {
          "id": "4c9f83e4-f479-48d0-9f92-3fff70a8f6ba",
             "item":
"{"business":"1114","class":"Demo","date":"01-01-2014","version":"","data":"dummy","name":"Finance"}"

        }

I need to get the values of business, class, date etc and pass it as
params to my method. So I tried to convert it into hashes as below

    hash_item = JSON.parse (item)

and output in console shows as

    The converted hash item is
    {"guid"=>"4c9f83e4-f479-48d0-9f92-3fff70a8f6ba",
"item"=>"{"business":"1114","class":"Demo","date":"01-01-2014","version":"","data":"dummy","name":"Finance"}"}

But when I try to access the hash value for business as
`hash_item['item']['business']` it shows

> "business"

 since the value of item is a String in the hash_item. I am not sure
whether my approach is correct or not. So is there any better idea or
any inputs to retrieve the hash values . Please help.
571b84c7de90293b010f39449b37c9e4?d=identicon&s=25 Carl Schwope (lowest0ne)
on 2014-05-09 00:43
My first post here, sorry about formating ( or lack there of ).

"item": "{"business":"111 ... ... ;}"

You get "business" because the value of item['item'] is a string.  The
[] operator on a string returns the enclosed string if that substring
exists in the string:

my_string = "Hello World"
my_string[ "llo" ] => "llo"

So that is the first issue, that string needs to have a JSON.parse
called on it.  However, it is also escaped.  I'm not sure that the
JSON.parse with unescape it for you, but CGI will:

require 'cgi'

string = ""business":"
CGI.unescapeHTML( string ) => "\"business\":"

So, you want something like:

parsed = JSON.parse( original )
parsed['item'] = JSON.parse( CGI.unescapeHTMl( parsed['item'] ) )
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2014-05-09 06:17
> My first post here

Nice answer.
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.