ABCD
ABCD

Reputation: 11

Ruby: accessing elements

I have output of the form

{\"id\":\"anon\",\"source\":\"abc\",\"word_count_message\":\"There were 268 words\"}" 

stored in variable x

I need to access the field "word_count"

x.inspect 

prints

"{\"id\":\"anon\",\"source\":\"abc\",\"word_count\":268}"

x["word_count"] prints word_count instead of "There were 268 words"

What am I missing here?

Upvotes: 0

Views: 35

Answers (2)

Troy SK
Troy SK

Reputation: 1289

h = JSON.parse(x)
puts h["word_count_message"] to get the result.

Upvotes: 1

Jason
Jason

Reputation: 2743

I'm sure there's cleaner ways to accomplish this, but this works:

h = Hash[x.tr('"{}\\', '').split(",").collect{|kv| [kv.split(":")[0], kv.split(":")[1]]}]

I took out the double quotes, brackets and extra \'s. Then I split it into an array using the commas as the delimiters. Then I changed each element of that array into a 2-element, key/value array using the :'s as delimiters. Then I turned the whole thing into a Hash.

p h
p h["word_count_message"]

Output:

{"id"=>"anon", "source"=>"abc", "word_count_message"=>"There were 268 words"}
"There were 268 words"

Upvotes: 0

Related Questions