Search code examples
rubyjsonpretty-printbraces

Ruby: how to generate a json output with braces (brackets, parentheses, curlies) in a new line


for a reference file compare a need the possibility to generate json files, where braces always start in a new line.

For Instance, the json hash:

my_json = {"Key" => {"Key" => "Value"}}

leads after the call of

JSON.pretty_generate(my_json)

to

{
  "Key": {
    "Key": "Value"
  }
}

But unfortunately I need an output like this:

{
  "Key": 
  {
    "Key": "Value"
  }
}

Is there any way to this with ruby without destroying the pretty formatting?

Thanks


Solution

  • Should you desire this difference in output, why don't you force it? As per my comment:

    UPDATED to cover both { and [ bracket

    my_json = {"Keys" => [{"Key" => "Value"},{"key1" => "val2"}], "newkey" => {"nk1" => "val3"}}
    
    puts JSON::pretty_generate(my_json).gsub(
               /^(.*)(\"[^\"]+\"): ([\{\[])/, #first brackets: white space. Second: Key, Third: Bracket
               "\\1\\2:\n\\1\\3")             #\\1: white space (on both lines), \\2: Key, \\3: Brac[e|ket]
    
    {
      "Keys":
      [
        {
          "Key": "Value"
        },
        {
          "key1": "val2"
        }
      ],
      "newkey":
      {
        "nk1": "val3"
      }
    }