How to pretty format JSON output in Ruby on Rails| Prettier JSON in Ruby with examples

Sometimes, We have a JSON string, and want to print it to console

For example, json string is in the ruby object

employee = '{ "id":"1", "name":"john", "age":"30" }'
puts employee

It prints in a single line without format and indentation. Output:

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

This prints json objects in the same line without format. It is difficult to read the object.

It is very easy to read If you print the json object in a nice format. Then, How do you pretty print json with a nice format in Ruby?

How to format json in Ruby with example?

json library provides the pretty_generate method which takes parsed json valid string and returned the pretty formatted json object.

Here is an example code

require 'json'

employee = '{ "id":"1", "name":"john", "age":"30" }'
puts employee
puts JSON.pretty_generate(JSON.parse(employee))

Output:

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

Pretty print json object to Browser console using ruby on rails code

Sometimes, We want to print an object as json to chrome(any browser) console.

Here is a code in ruby on rails

console.log("<%= j JSON.pretty_generate(@v).html_safe %>");

Output:

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

if you want to display pretty formatted json in view or HTML on the web page.

<% if @employee.present? %>

   <pre><%= JSON.pretty_generate(@employee) %></pre>

<% end %>

It displays pretty printed objects on the web page.

Pretty print json object with awesome_print

awesome_print🔗 library provides a ruby object to formatted as JSOn with colored styles and indentation.

You have to import json and awesome_print into your code. call JSON.parse() method and returns pretty json.

Here is an example code

require "awesome_print"
require "json"

json =  '{ "id":"1", "name":"john", "age":"30" }'

puts JSON.parse(json)

Conclusion

To summarize,

You can use inbuilt json package for basic indentation and format. If you want full pledge colored styles and proper indentation, you can use awesome_print package.