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
ifNaN
,Infinity
, and-Infinity
should be generated, otherwise an exception is thrown if these values are encountered. This options defaults tofalse
.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 to100
.
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
Factorygirl Association Model Trouble: "Systemstackerror: Stack Level Too Deep"
Why Is Ruby Unable to Verify an Ssl Certificate
Expected to Define. When Calling Class Inside a Module
Ruby Open-Uri Redirect Forbidden
How to Find the Ruby Interpreter
The Encoding That Notepad++ Just Calls "Ansi", Does Anyone Know What to Call It for Ruby
Rails: Opposite of Hash#To_Param
How Does Rails Csrf Protection Work
Converting Utf8 to Ansi with Ruby
Failed to Build Gem Native Extension' on Windows 7 (The System Cannot Find the Path Specified)
Getting Webpage Content with Ruby -- I'm Having Troubles
Rails Simpleform with Non-Model Inputs
Selenium Rc: Run Tests in Multiple Browsers Automatically
Passenger: Internal Server Error
How to Sort Authors by Their Book Count with Activerecord
What's the Difference Between the Build and Create Methods in Factorygirl
How to Write a Shell Script That Starts Tmux Session, and Then Runs a Ruby Script