George Ananda Eman George Ananda Eman - 1 year ago 120
Ruby Question

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

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


Why cant i do the line break?

Answer Source

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


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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download