This project is archived and is in readonly mode.

#5425 ✓stale
John Ryding

Create a JSON builder for resource representations

Reported by John Ryding | August 21st, 2010 @ 05:24 PM

Rails does not include a way to create a custom JSON representation of a resource that follows the patterns of creating other representations.

From my understanding, a View defines the format and templates of how a resource is sent back to the client and one can easily define HTML and XML representations through the use of files like "show.html.erb" and "show.xml.builder". However, when trying to create a custom JSON representation, one must go into their Model file and override the as_json method, which is inconsistent with how other representations are defined.

Also, when trying to define custom JSON representations that include associations, one must rely on the associations to define their JSON representation when the parent resource may not care about using all of that data.

For example, consider a student that has_many courses. A developer might want their JSON representation to include courses like so:

{
  //...a bunch of data about the student...//
  courses: [
    <uri root>/courses/123,
    <uri root>/courses/143,
    <uri root>/courses/1653,
    <uri root>/courses/15436
  ]
}

however, as_json only allows a developer to access the courses resource like so:

def as_json(options={})
  {
    # ...student data...
    :courses => self.courses
  }
end

which makes the JSON representation of a student's courses bound to the JSON representation of a course:

{
  /*...a bunch of data about the student...*/
  courses: [
    { /*...all course data...*/ },
    { /*...all course data...*/ },
    { /*...all course data...*/ },
    { /*...all course data...*/ },
  ]
}

Lastly, there is a method to use the XML Builder view to create a JSON representation, but is a method that requires some hacking of code to do:

http://web.archive.org/web/20080205212821/http://blog.tagteamintera... (See "Sexy REST in Rails" section)

Edited by Rohit Arondekar for formating.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Pages