Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

ruby

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?

like image 385
George Ananda Eman Avatar asked Aug 28 '13 17:08

George Ananda Eman


1 Answers

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.
like image 189
Mulan Avatar answered Oct 11 '22 16:10

Mulan