Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "pretty" format JSON output in Ruby on Rails

I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.

Right now, I call to_json and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.

Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?

like image 487
JP Richardson Avatar asked Sep 17 '08 19:09

JP Richardson


People also ask

How do I make JSON data pretty?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

How do I use beautify postman?

You can use variables in your body data and Postman will populate their current values when sending your request. To beautify your XML or JSON, select the text in the editor and then select ⌘+Option+B or Ctrl+Alt+B.

What is JSON format?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).


2 Answers

The <pre> tag in HTML, used with JSON.pretty_generate, will render the JSON pretty in your view. I was so happy when my illustrious boss showed me this:

<% if @data.present? %>    <pre><%= JSON.pretty_generate(@data) %></pre> <% end %> 
like image 37
Roger Garza Avatar answered Sep 20 '22 10:09

Roger Garza


Use the pretty_generate() function, built into later versions of JSON. For example:

require 'json' my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" } puts JSON.pretty_generate(my_object) 

Which gets you:

{   "array": [     1,     2,     3,     {       "sample": "hash"     }   ],   "foo": "bar" } 
like image 101
lambshaanxy Avatar answered Sep 23 '22 10:09

lambshaanxy