0

I need a pretty output of the JSON for an activerecord object in the rails controller. Based on the answer to this question by jpatokal, I tried the following:

respond_to do |format|
  format.json { render :json => JSON.pretty_generate(record) }
end 

where

record 

is an activerecord object. It does not produce a prettified output. However, when I try outputting a hash using the same code, viz,

respond_to do |format|
  format.json { render :json => JSON.pretty_generate({"abc" => "1", "def" => "2"}) }
end 

it does produce a prettified output (so pretty_generate is working, and so is my browser).

How do I use pretty_generate to produce a pretty output of an activerecord object?

Community
  • 1
  • 1
ppd
  • 69
  • 9
  • presuming you explicity added `gem install json` to your Gemfile? – blotto Feb 12 '14 at 00:18
  • I didn't. However, it is there: $ gem list | grep "json" json (1.7.5) multi_json (1.3.6) – ppd Feb 12 '14 at 00:23
  • my suggestion is to try in rails console next, and exclude the format.json code. basically see if `> JSON.pretty_generate(record)` exhibits the \n chars. – blotto Feb 12 '14 at 00:42
  • Thanks for that tip. In the console, record.to_json produces the json for the object. However, `> JSON.pretty_generate(record)` gives the following error: `NoMethodError: undefined method 'key?' for #`. It appears that record cannot be serialized correctly? – ppd Feb 12 '14 at 00:59
  • sounds like the instance is a complex object, not easily serlialized. try some other json parser like `gem yajl-ruby` – blotto Feb 12 '14 at 01:06
  • before that, maybe even try `JSON.pretty_generate(record.as_json)` and/or `JSON.pretty_generate(record.to_json)` in console – blotto Feb 12 '14 at 01:08

1 Answers1

6

To get pretty output of JSON from an active record object you have to first request the object as JSON.

record.as_json

The above code will do this for you, the short way to render out pretty JSON from the controller is:

render json: JSON.pretty_generate(record.as_json)

This also solves the "only generation of JSON objects or arrays allowed" error you can get trying to convert AR objects to pretty_generate JSON.


EDIT: I forgot to mention this can all be done in rails 4.1.8 and above (possibly even earlier) using the standard json and multi-json gems packaged with rails project.

AdrieanKhisbe
  • 3,899
  • 8
  • 37
  • 45
Andrew G
  • 76
  • 1
  • 2