Rails - How can I display nicely indented JSON?
Asked Answered
G

4

7

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.

Ghetto answered 20/5, 2010 at 14:6 Comment(0)
E
4

Use JSON.pretty_generate(object)

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

Enjoy answered 16/11, 2010 at 21:8 Comment(0)
G
3

This will only work with Firefox, but assuming you just need pretty json to help you or other developers during development you should check out the JSONview addon for Firefox (it has made my life easier):

https://addons.mozilla.org/en-US/firefox/addon/10869/

If you want to have a pretty json available to all users regardless of browser, I don't have a good solution to offer.

Gentle answered 21/5, 2010 at 5:2 Comment(1)
chrome.google.com/webstore/detail/jsonview/… Here you have something similar for Chrome. This is what I use regularly and I find it quite useful.Israelisraeli
C
3

you can use this

render json: JSON.pretty_generate(data)
Cata answered 16/5, 2013 at 9:59 Comment(2)
I did JSON.pretty_generate(user.attributes) where user is an ActiveRecord object.Pressey
you can use user.to_jsonCata
A
0

jsonpp is a great command line tool for formatting (pretty printing) JSON.

You can pipe your JSON into it:

curl -s -L http://t.co/tYTq5Pu | jsonpp
Altostratus answered 20/5, 2013 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.