0

In my model i'm getting two Json arrays from both the facebook's and twitter's api.

facebook_friends = { "data": 
  [{"name": "Friend Joe", "id": "123"}, 
   {"name": "Friend Jane", "id": "12342"}]}
twitter_friends = { "users": 
  [{"name": "Other friend joe", "id": "333"}, 
   {"name": "Other friend Jane", "id": "456"}]}

And I want to build an array like this (NB: i'm appending the provider key to identify the source of the data)

all_friends = [
  {"name": "Friend Joe", "id": "123", "provider": "facebook"},
  {"name": "Friend Jane", "id": "12342", "provider": "facebook"}, 
  {"name": "Other friend joe", "id": "333", "provider": "twitter"},
  {"name": "Other friend Jane", "id": "456", "provider": "twitter"}]

I can do this with jquery like this -> http://jsfiddle.net/gm3jJ/ but how do i do it in ruby?
Thanks

2 Answers 2

1

If you want to combine stuff, you can just do it like this:

# Get the array of friends from each service and add provider
fb = JSON.parse(facebook_friends)["data"].map {|x| x["provider"] = "facebook"}
tw = JSON.parse(twitter_friends)["users"].map {|x| x["provider"] = "twitter"}
# Concatenate them into one array
fb + tw
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this using those lines:

facebook_array = JSON.parse('{ "data": [{"name": "Friend Joe", "id": "123"}, {"name": "Friend Jane", "id": "12342"}]}')["data"].map{|h| h.merge({'provider' => 'facebook'})}
twitter_array = (JSON.parse('[{"name": "Other friend joe", "id": "333"}, {"name": "Other friend Jane", "id": "456"}]').map{|h| h.merge({'provider' => 'twitter'})})
final_array = facebook_array.concat(twitter_array)

Edit: Don't forget to require json, like this before executing the above code: require 'json'

3 Comments

Thanks, is final_array a json array?
no, it isn't a json array, it is a ruby array. You can get a json array back by doing final_array.to_json, and it will be yours :)
All the pleasure is mine Don't forget to click on "accepted answer" on the left of my answer please :-)

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.