0

I am trying to loop through a hash for specific data to output. If I want to output all usernames. This is how I can do it one at a time but its not what I want.

puts username = json["users"][0]["username"]
puts username = json["users"][1]["username"]

also tried

json.each { |x| puts json["users"][x]["username"]}

This is the hash structure

{"success"=>true, "users"=>[{"id"=>"1523493", "username"=>"myname","age"=>"21"},{"id"=>"653172", "username"=>"anothername","age"=>"65"}]}

sorry I didnt make my question clear enough. I am wanting to iterate the hash for "username" and then i can loop through each username and output specific data before moving to next username

1
  • also users.map { |entry| puts entry["usersname"]} gives me an error no implicit conversion of String into Integer Commented Nov 15, 2015 at 7:15

3 Answers 3

1

You can loop your json like this

json["users"].each do |u|
   username = u["username"]
   #Do some logic with username
   #like user = User.find_by_username(username)
end
Sign up to request clarification or add additional context in comments.

Comments

1

You can get all the usernames in one go by doing something like this:

json = { "users" => [{"id"=>"1523493", "username"=>"myname"},{"id"=>"653172", "username"=>"anothername"}] }

json["users"].map { |user| user["username"] }
# => ["username", "anothername"]

The above will provide you with an array of usernames to do with as you see fit. :)

Hope it helps!

1 Comment

Sorry I didnt make my question clear enough I think. For each occurrence of "username" I would like to use it as the loop so I then can extract the elements I need. also I didnt post the proper hash and have now corrected it.
0
h = {"success"=>true, 
     "users"=>[{"id"=>"1523493", "username"=>"myname","age"=>"21"},
               {"id"=>"653172", "username"=>"anothername","age"=>"65"}]}

h["users"].map { |user| user["username"] }
   #=> ["myname", "anothername"] 

1 Comment

that does work great but, I have updated my quest because I wasnt clear enough and i posted the wrong hash structure, sorry.

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.