Rails - How can I display nicely indented JSON?

Posted by sa125 on Stack Overflow See other posts from Stack Overflow or by sa125
Published on 2010-05-20T14:06:12Z Indexed on 2010/05/23 13:40 UTC
Read the original article Hit count: 453

Filed under:
|
|

Hi -

I have a controller action that returns JSON data for api purposes, and plenty of it. I want to be able to inspect it in the browser, and have it nicely indented for the viewer. For example, if my data is

data = { :person => { :id => 1, :name => "john doe", :age => 30 }, :person => ... }

I want to see

{ "person" : 
    { 
        "id"   : 1, 
        "name" : "john doe",
        "age"  : 30,
    }, 

   "person" : 
    { 
        "id"   : 2, 
        "name" : "jane doe",
        "age"  : 31,
    },

    ...etc
}

In the view.

I thought about using different routes to get the bulk/pretty data:

# GET /api/json
# ...
respond_to do |format|
  format.html { render :json => data.to_json }
end

# GET /api/json/inspect
# ...
respond_to do |format|
  format.html { render :text => pretty_json }
end

Anyone knows of a gem/plugin that does this or something similar? I tried using JSON.pretty_generate, but it doesn't seem to work inside rails (2.3.5). thanks.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about JSON