premunk
premunk

Reputation: 433

Ruby: Embedded Ruby Array of hashes to JSON

I am trying to convert the Ruby array of hashes to a JSON and return it.

What I've tried so far:

hash ={}
user.attributes.each_pair do |key, value|
  if(key == 'auth_id')
     hash[key] = value
  elsif (key == 'useractivity')
     # How do I get to the Key's array of useractivities from here?
     # {useractivities : [{id:,:name},{:id,:name}]}
  end
end
return hash.to_json

Thanks!

Upvotes: 0

Views: 474

Answers (1)

Saurabh
Saurabh

Reputation: 73659

You can do:

hash ={}
user.attributes.each_pair do |key, value|
  if(key == 'auth_id')
     hash[key] = value
  elsif (key == 'useractivity')
     value.each {|inner_hash|   do_something_on_inner_hash}

     # How do I get to the Key's array of useractivities from here?
     # {useractivities : [{id:,:name},{:id,:name}]}
  end
end
return hash.to_json

Upvotes: 1

Related Questions