How to "Pretty" Format Json Output in Ruby on Rails

How to pretty format JSON output in Ruby on Rails

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": [
"sample": "hash"
"foo": "bar"

Pretty format my JSON output in Rails 4

As the error suggest, only generation of JSON objects or arrays allowed. I guess you should try this.

@celebrities = Celebrity.includes(:category)    
respond_to do |format|
format.json { render json: JSON.pretty_generate(JSON.parse(@celebrities.to_json(:include =>{:category => {:only => [:category]} })))}

Rails: Pretty print JSON without overkill

Use this helper method built into JSON.


I just tried and it works:

> str = '{"error":{"type":"unauthorized","message":"This page cannot be accessed without a valid API key."}}'
> JSON.pretty_generate(JSON.parse(str))
=> "{\n \"error\": {\n \"type\": \"unauthorized\",\n \"message\": \"This page cannot be accessed without a valid API key.\"\n }\n}"

Rails 4 Pretty JSON output

That's probably your browser being nice to you. There are lots of extensions for Chrome and Firefox that will automatically format your JSON for you:

  • Chrome: JSON Formatter
  • Chrome: JSON Viewer
  • Firefox: JSONView
  • Firefox: JSONovich
  • Safari JSON Formatter

You don't really want Rails to handle the pretty printing for you since that would dramatically increase the size of your JSON responses.

How can I prettify json output for ActiveAdmin?

I would go with something like this:

show do
attributes_table do
row :source_json do |model|

You might not need the JSON.parse call if you have an option to get source as a Ruby hash instead of a JSON string.

You might want to wrap the output into a <pre> HTML tag – like Evan Ross suggested – to improve readability:

show do
attributes_table do
row :source_json do |model|
tag.pre JSON.pretty_generate(JSON.parse(model.source_json))

How to properly format json to send over using RestClient

You should put all your params in one params hash like this:

  params = {
recipient: { id: sender },
message: { text: text },
access_token: page_token

response = base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
p "this is the response #{response}"

Related Topics

Leave a reply