Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How can I display nicely indented JSON?

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.

like image 676
sa125 Avatar asked May 20 '10 14:05

sa125


People also ask

How do I indent JSON?

JSON conventions¶Use four spaces for indentation (matching OpenStack conventions used in Python and shell scripts). Do not use tab characters in the code, always use spaces. Use one space after the name-separator (colon). Obey the formal JSON format; in particular, wrap strings in double (not single) quotes.


1 Answers

Use JSON.pretty_generate(object)

http://flori.github.com/json/doc/classes/JSON.html#method-i-pretty_generate

like image 82
mml Avatar answered Nov 07 '22 15:11

mml