In Ruby, How to Output JSON from Hash and Give It Line Breaks and Tabs

In Ruby, how to output json from hash and give it line breaks and tabs

Yay for pretty things and yay for avoiding regexen!

Use the built-in JSON.pretty_generate method

require 'json'
puts JSON.pretty_generate hash, options

Yay!

Here's the options:

  • indent: a string used to indent levels (default: ''),
  • space: a string that is put after, a : or , delimiter (default: ''),
  • space_before: a string that is put before a : pair delimiter (default: ''),
  • object_nl: a string that is put at the end of a JSON object (default: ''),
  • array_nl: a string that is put at the end of a JSON array (default: ''),
  • allow_nan: true if NaN, Infinity, and -Infinity should be generated, otherwise an exception is thrown if these values are encountered. This options defaults to false.
  • max_nesting: The maximum depth of nesting allowed in the data structures from which JSON is to be generated. Disable depth checking with :max_nesting => false, it defaults to 100.

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": [
1,
2,
3,
{
"sample": "hash"
}
],
"foo": "bar"
}

How can I remove the string \n from within a Ruby string?

You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.

Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.

While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.

In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.

See here for more info

More beautiful, indented, pretty-printing

You might want to try the AwesomePrint gem which would return the following by default (the actual output is colored) and is customizable:

aoa = [ [1,2,3], [4,5,6] ]
#=> [
# [0] [
# [0] 1,
# [1] 2,
# [2] 3
# ],
# [1] [
# [0] 4,
# [1] 5,
# [2] 6
# ]
# ]

Ruby: Can I write multi-line string with no concatenation?

There are pieces to this answer that helped me get what I needed (easy multi-line concatenation WITHOUT extra whitespace), but since none of the actual answers had it, I'm compiling them here:

str = 'this is a multi-line string'\
' using implicit concatenation'\
' to prevent spare \n\'s'

=> "this is a multi-line string using implicit concatenation to eliminate spare
\\n's"

As a bonus, here's a version using funny HEREDOC syntax (via this link):

p <<END_SQL.gsub(/\s+/, " ").strip
SELECT * FROM users
ORDER BY users.id DESC
END_SQL
# >> "SELECT * FROM users ORDER BY users.id DESC"

The latter would mostly be for situations that required more flexibility in the processing. I personally don't like it, it puts the processing in a weird place w.r.t. the string (i.e., in front of it, but using instance methods that usually come afterward), but it's there. Note that if you are indenting the last END_SQL identifier (which is common, since this is probably inside a function or module), you will need to use the hyphenated syntax (that is, p <<-END_SQL instead of p <<END_SQL). Otherwise, the indenting whitespace causes the identifier to be interpreted as a continuation of the string.

This doesn't save much typing, but it looks nicer than using + signs, to me.

Also (I say in an edit, several years later), if you're using Ruby 2.3+, the operator <<~ is also available, which removes extra indentation from the final string. You should be able to remove the .gsub invocation, in that case (although it might depend on both the starting indentation and your final needs).

EDIT: Adding one more:

p %{
SELECT * FROM users
ORDER BY users.id DESC
}.gsub(/\s+/, " ").strip
# >> "SELECT * FROM users ORDER BY users.id DESC"


Related Topics



Leave a reply



Submit