ppd
ppd

Reputation: 69

Rails: JSON.pretty_generate(obj) in the controller does not produce pretty output

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?

Upvotes: 0

Views: 2195

Answers (1)

Andrew G
Andrew G

Reputation: 76

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.

Upvotes: 6

Related Questions