views:

592

answers:

3

The default way to output JSON in rails is some thing like:
Code:
render :json => friends.to_json(:only => [:username, :avatar_file_name, :id ])

Output

{"friends" : 
  [{"user": 
    {"avatar_file_name": "image1.jpg", "username": "user1", "id": 1}},
   {"user": 
    {"avatar_file_name": "image2.jpg", "username": "user2", "id": 2}},
   {"user":
    {"avatar_file_name": "image3.jpg", "username": "user3", "id": 3}}
  ]}

But i want something like:

{"friends" : 
    {"user": [
      {"avatar_file_name": "image1.jpg", "username": "user1", "id": 1},
      {"avatar_file_name": "image2.jpg", "username": "user2", "id": 2},
      {"avatar_file_name": "image3.jpg", "username": "user3", "id": 3}
    ]}
}

The class is specified by the array name.
Last.fm also uses this syntax see Last.fm 'API-user.getfriends'

A: 

You can use javascript to reformat it:

var json = 
{
  "friends" : 
  { "user": [] }
}

var i = 0;
for ( x in friends )
{
     json.friends.user[i].avatar_file_name = x.user.avatar_file_name; // add more fields.
     i++;
}

Something among those lines.

the_drow
The output is going to be used in an iphone app. So the output will not be parsed via javascript but directly converted to objective-C objects. I want the right json file directly from rails. Thank you for your aswer.
FGeertsema
No problem. Anytime.
the_drow
A: 

JSON is normally used to represent objects in a text format.

So if you like the secon output you must change your objects.

The first output says: there is a friends object which is a array of user, each user has some properties among which you chose to expose *username, avatar_file_name, id*

The second output says: there is a friends object which contains a user object which is an array of unnamed objects, each unnamed objects has some properties...

This second output is not writable in JSON syntax.

It might be:

{"friends" : 
    {"user": [
      ["avatar_file_name", "username", "id"],
      ["image1.jpg", "user1", 1],
      ["image2.jpg", "user2", 2],
      ["image3.jpg", "user3", 3]
    ]}
}

This says: there is a friends object which contains a user object which is an array of array (a table with field names on first row) ...

Han Fastolfe
I believe you are wrong about the second output.
the_drow
Last.fm also uses the same syntax as my second output. See edited question.
FGeertsema
+2  A: 

The solution to this problem is commenting the line
ActiveRecord::Base.include_root_in_json = true
in initializers/new_rails_defaults.rb

Or setting ActiveRecord::Base.include_root_in_json to false.

FGeertsema