0

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!

2
  • 2
    Can you show what you're starting off with and what you're trying to get it to look like? Commented Apr 18, 2015 at 0:25
  • Are you looking for: hash[key] = value[:useractivities]? Commented Apr 18, 2015 at 4:11

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, Ok. But If I want my inner hash to be a part of the hash, How can I do that? The issue is that whenever I try to display the useractivity in my route, I always get an empty JSON.
Can you provide a sample input and sample output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.