I\'m trying to format {\"key\" => \"value\"}
to turn it into :
{
\"key\" : \"value\"
}
for writing into a json file. ri
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
.As @naomik mentions, try using the builtin JSON.pretty_generate with a tab for the "indent" option, for example:
require 'json'
h = {:key => :value}
puts JSON.pretty_generate(h, :indent => "\t")
# {
# "key": "value"
# }
The values for the "opts" argument to pretty_generate
are documented at generate.
For both line breaks and tabs, try
require 'json'
hash = {foo: 'bar'}
JSON.pretty_generate(hash, {indent: "\t", object_nl: "\n"})
NB! If you use single quotes with newlines ("\n") or tabs ("\t") they will not be interpreted as newlines but as an ordinary string containing one backslash and a letter. This is a common mistake. :)