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?
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.
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.
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).
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 %>
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With