{

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to print the name of a Ruby class| Ruby on Rails By Example

How to check if the variable is defined in Ruby with examples

How to Find the minimum and maximum values in an array and hash Ruby with examples

How to Generate Random number in Ruby with examples