Best way to pretty print a hash
RubyRuby on-Rails-3Ruby Problem Overview
I have a large hash with nested arrays and hashes. I would like to simply print it out so it 'readable' to the user.
I would like it to be sort of like to_yaml - that's pretty readable - but still too tech looking.
Ultimately its going to be end users who need to read these data chunks so they need to be formatted cleanly.
Any suggestions?
Ruby Solutions
Solution 1 - Ruby
require 'pp'
pp my_hash
Use pp
if you need a built-in solution and just want reasonable line breaks.
Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false
option to turn off displaying array indices.)
Solution 2 - Ruby
If you have JSON, I recommend JSON.pretty_generate(hash)
because it is simpler than awesome_print, looks great in a pre
tag, and allows for easy copying from a web page. (See also: https://stackoverflow.com/questions/86653/how-can-i-pretty-format-my-json-output-in-ruby-on-rails)
Solution 3 - Ruby
Another solution which works better for me than pp
or awesome_print
:
require 'pry' # must install the gem... but you ALWAYS want pry installed anyways
Pry::ColorPrinter.pp(obj)
Solution 4 - Ruby
If you don't have any fancy gem action, but do have JSON, this CLI line will work on a hash:
puts JSON.pretty_generate(my_hash).gsub(":", " =>")
#=>
{
:key1 => "value1",
:key2 => "value2",
:key3 => "value3"
}
Solution 5 - Ruby
Use the answers above if you're printing to users.
If you only want to print it for yourself in console, I suggest using the pry gem instead of irb. Besides pretty printing, pry has a lot of other features as well (check railscast below)
> gem install pry
And check this railscast:
Solution 6 - Ruby
In Rails
If you need
- a "pretty printed" Hash
- in e.g. the Rails.logger
- that, specifically, runs
inspect
on the objects in the Hash- which is useful if you override/define the
inspect
method in your objects like you're supposed to
- which is useful if you override/define the
... then this works great! (And gets better, the bigger and more nested your Hash object is.)
logger.error my_hash.pretty_inspect
For example:
class MyObject1
def inspect
"<#{'*' * 10} My Object 1 #{'*' * 10}>"
end
end
class MyObject2
def inspect
"<#{'*' * 10} My Object 2 #{'*' * 10}>"
end
end
my_hash = { a: 1, b: MyObject1.new, MyObject2.new => 3 }
Rails.logger.error my_hash
# {:a=>1, :b=><********** My Object 1 **********>, <********** My Object 2 **********>=>3}
# EW! ^
Rails.logger.error my_hash.pretty_inspect
# {:a=>1,
# :b=><********** My Object 1 **********>,
# <********** My Object 2 **********>=>3}
pretty_inspect
comes from PrettyPrint, which rails includes by default. So, no gems needed and no conversion to JSON needed.
Not In Rails
If you're not in Rails or if the above fails for some reason, try using require "pp"
first. For example:
require "pp" # <-----------
class MyObject1
def inspect
"<#{'*' * 10} My Object 1 #{'*' * 10}>"
end
end
class MyObject2
def inspect
"<#{'*' * 10} My Object 2 #{'*' * 10}>"
end
end
my_hash = { a: 1, b: MyObject1.new, MyObject2.new => 3 }
puts my_hash
# {:a=>1, :b=><********** My Object 1 **********>, <********** My Object 2 **********>=>3}
# EW! ^
puts my_hash.pretty_inspect
# {:a=>1,
# :b=><********** My Object 1 **********>,
# <********** My Object 2 **********>=>3}
A Full Example
Big ol' pretty_inspect
ed Hash example from my project with project-specific text from my inspected objects redacted:
{<***::******************[**:****, ************************:****]********* * ****** ******************** **** :: *********** - *** ******* *********>=>
{:errors=>
["************ ************ ********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
"************ ************ ********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
"************ ************ ********** ***** ****** ******** is invalid",
"************ ************ ********** is invalid",
"************ ************ is invalid",
"************ is invalid"],
:************=>
[{<***::**********[**:****, *************:**, ******************:*, ***********************:****] :: **** **** ****>=>
{:************=>
[{<***::***********[**:*****, *************:****, *******************:**]******* :: *** - ******* ***** - *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: *** - *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ********* - *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ********** - ********** *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ******** - *>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: **** - *******>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: *** - ********** ***** - *>=>
{}}]}},
{<***::**********[**:****, *************:**, ******************:*, ***********************:****] ******************** :: *** - *****>=>
{:errors=>
["************ ********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
"************ ********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
"************ ********** ***** ****** ******** is invalid",
"************ ********** is invalid",
"************ is invalid"],
:************=>
[{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]*********** :: ****>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *******>=>
{:errors=>
["********** ***** ****** ******** ***** ****** ******** **** ********** **** ***** ***** ******* ******",
"********** ***** ****** ******** ***** ****** ******** **** ********** is invalid",
"********** ***** ****** ******** is invalid",
"********** is invalid"],
:**********************=>
[{<***::*******************[**:******, ************************:***]****-************ ******************** ***: * :: *** - ***** * ****** ** - ******* * **: *******>=>
{:errors=>
["***** ****** ******** **** ********** **** ***** ***** ******* ******",
"***** ****** ******** **** ********** is invalid"],
:***************=>
[{<***::********************************[**:******, *************:******, ***********:******, ***********:"************ ************"]** * *** * ****-******* * ******** * ********* ******************** *********************: ***** :: "**** *" -> "">=>
{:errors=>["**** ***** ***** ******* ******"],
:**********=>
{<***::*****************[**:******, ****************:["****** ***", "****** ***", "****** ****", "******* ***", "******* ****", "******* ***", "****"], **:""] :: "**** *" -> "">=>
{:errors=>
["***** ******* ******",
"***** ******* ******"]}}}}]}}]}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:**]******* :: ****** - ** - *********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - ********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
{}},
{<***::***********[**:*****, *************:****, *******************:***]******* :: ****** - ** - **********>=>
{}}]}}]}}
Solution 7 - Ruby
Pretty Print Hash
using pure Ruby (no gems)
I came across this thread trying to solve this problem for myself.
I had a large Hash
that I wanted to make pretty, but I needed to stay in ruby hash notation instead of JSON.
This is the code + examples
- Use pretty_generate to get a nice formatted JSON string.
- Replace all the JSON keys with
symbol:
equivalent
puts JSON.pretty_generate(result)
.gsub(/(?:\"|\')(?<key>[^"]*)(?:\"|\')(?=:)(?:\:)/) { |_|
"#{Regexp.last_match(:key)}:"
}
Sample JSON
{
"extensions": {
"heading": "extensions",
"take": "all",
"array_columns": [
"name"
]
},
"tables": {
"heading": "tables",
"take": "all",
"array_columns": [
"name"
]
},
"foreign_keys": {
"heading": "foreign_keys",
"take": "all",
"array_columns": [
"name"
]
},
"all_indexes": {
"heading": "all_indexes",
"take": "all",
"array_columns": [
"name"
]
},
"keys": {
"heading": "keys",
"take": "all",
"array_columns": [
"name"
]
}
}
Sample Ruby Hash
{
extensions: {
heading: "extensions",
take: "all",
array_columns: [
"name"
]
},
tables: {
heading: "tables",
take: "all",
array_columns: [
"name"
]
},
foreign_keys: {
heading: "foreign_keys",
take: "all",
array_columns: [
"name"
]
},
all_indexes: {
heading: "all_indexes",
take: "all",
array_columns: [
"name"
]
},
keys: {
heading: "keys",
take: "all",
array_columns: [
"name"
]
}
}
Solution 8 - Ruby
Easy to do with json if you trust your keys to be sane:
JSON.pretty_generate(a: 1, 2 => 3, 3 => nil).
gsub(": null", ": nil").
gsub(/(^\s*)"([a-zA-Z][a-zA-Z\d_]*)":/, "\\1\\2:"). # "foo": 1 -> foo: 1
gsub(/(^\s*)(".*?"):/, "\\1\\2 =>") # "123": 1 -> "123" => 1
{
a: 1,
"2" => 3,
"3" => nil
}
Solution 9 - Ruby
Using Pry you just need to add the following code to your ~/.pryrc:
require "awesome_print"
AwesomePrint.pry!
Solution 10 - Ruby
Of all the gems I tried, show_data
gem worked the best for me, I now use it extensively to log params hash in Rails pretty much all the time
Solution 11 - Ruby
Here's another approach using json and rouge:
require 'json'
require 'rouge'
formatter = Rouge::Formatters::Terminal256.new
json_lexer = Rouge::Lexers::JSON.new
puts formatter.format(json_lexer.lex(JSON.pretty_generate(JSON.parse(response))))
(parses response from e.g. RestClient
)
Solution 12 - Ruby
For large nested hashes this script could be helpful for you. It prints a nested hash in a nice python/like syntax with only indents to make it easy to copy.
module PrettyHash
# Usage: PrettyHash.call(nested_hash)
# Prints the nested hash in the easy to look on format
# Returns the amount of all values in the nested hash
def self.call(hash, level: 0, indent: 2)
unique_values_count = 0
hash.each do |k, v|
(level * indent).times { print ' ' }
print "#{k}:"
if v.is_a?(Hash)
puts
unique_values_count += call(v, level: level + 1, indent: indent)
else
puts " #{v}"
unique_values_count += 1
end
end
unique_values_count
end
end
Example usage:
h = {a: { b: { c: :d }, e: :f }, g: :i }
PrettyHash.call(h)
a:
b:
c: d
e: f
g: i
=> 3
The returned value is the count (3) of all the end-level values of the nested hash.
Solution 13 - Ruby
I came here through a search engine looking for a way to print hashes to end users in a human-readable format—particularly hashes with underscores in their keys.
Here's what I ended up doing using Rails 6.0.3.4:
hash.map do |key, val|
key.to_s.humanize + ': ' + val.to_s
end.join('; ')
# Turns {:foo_bar => 'baz', :fee_ber => :bez} into 'Foo bar: Baz; Fee ber: Bez'.
Solution 14 - Ruby
Under Rails, arrays and hashes in Ruby have built-in to_json functions. I would use JSON just because it is very readable within a web browser, e.g. Google Chrome.
That being said if you are concerned about it looking too "tech looking" you should probably write your own function that replaces the curly braces and square braces in your hashes and arrays with white-space and other characters.
Look up the gsub function for a very good way to do it. Keep playing around with different characters and different amounts of whitespace until you find something that looks appealing. http://ruby-doc.org/core-1.9.3/String.html#method-i-gsub