Skip to content

Instantly share code, notes, and snippets.

@georgkreimer
Created August 19, 2010 12:44
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save georgkreimer/537794 to your computer and use it in GitHub Desktop.
Save georgkreimer/537794 to your computer and use it in GitHub Desktop.
pretty print json in ruby
require 'json'
my_json = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_json)
Which gets you...
{
"array": [
1,
2,
3,
{
"sample": "hash"
}
],
"foo": "bar"
}
@kevinnio
Copy link

Yeah, but what if I want to put it into an HTML code block?

@a0x
Copy link

a0x commented Sep 25, 2017

Yes, I think this one is good.
Suppose I have an original json-format string: json_string.

require 'json'
json_string = '{"a": 1, "b":2}'
JSON.generate(JSON.parse(json_string)) # This will generate a pretty formatted one.

@kevinnio If you want to put it into a <code></code> block in Rails, then just do it, that't the Rails stuff.
If you also want some highlight, then you can try highlight.js.

@a2f0
Copy link

a2f0 commented Jul 16, 2019

A+ 🌈💯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment