Timmy Von Heiss
Timmy Von Heiss

Reputation: 2218

How do I search a json array that i am getting from a url and using httparty to parse?

This is the url:

https://meta.discourse.org/c/bug.json

I recovered the user_id of someone who started a topic. Now I need to use that user_id, which I have saved in an instance variable @id = 21509 to search the users array for the object whose id attribute is the same value as @id

I want to search:

{"users:[{"id":21509,"username":"ChrisBeach","avatar_template":"/user_avatar/meta.discourse.org/chrisbeach/{size}/56283_1.png"},{"id":1,"username":"sam","avatar_template":"/user_avatar/meta.discourse.org/sam/{size}/5243_1.png"},{"id":17592,"username":"AxelN","avatar_template":"/user_avatar/meta.discourse.org/axeln/{size}/47696_1.png"},{"id":8617,"username":"Mittineague","avatar_template":"/user_avatar/meta.discourse.org/mittineague/{size}/40997_1.png"},{"id":19,"username":"eviltrout","avatar_template":"/user_avatar/meta.discourse.org/eviltrout/{size}/5275_1.png"},{"id":9833,"username":"wesochuck","avatar_template":"/user_avatar/meta.discourse.org/wesochuck/{size}/20487_1.png"},

for the user object with key: id equal to value: @id and return the value of username for that object, in this case it would be ChrisBeach

Upvotes: 2

Views: 1797

Answers (1)

Timmy Von Heiss
Timmy Von Heiss

Reputation: 2218

@username = (['users'].find { |u| u['id'] == @id })['username'] 

Upvotes: 2

Related Questions