I'm trying to format {"key" => "value"} to turn it into :
{
"key" : "value"
}
for writing into a json file. right now im doing :
hash = {"key" => "value"}
puts hash.to_json.gsub('{', '{\n\t')
to start. and this outputs
{\n\t"key":"value"}
Why cant i do the line break?
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With