Phrogz / NeatJSON

Pretty-print your JSON in Ruby, JS, or Lua with more power than JSON.stringify or JSON.pretty_generate
http://phrogz.net/JS/NeatJSON
MIT License
108 stars 19 forks source link

neat formatting seems to ignore hash levels deeper than 2 #30

Closed fawaf closed 2 years ago

fawaf commented 4 years ago

the command to generate the below output is JSON.neat_generate(env, after_colon: 1, padding: 1). env contains the ruby hash object used to generate the output.

the output somehow has the _template hash all in one line, which is not expected:

{
  "name": "foo",
  "description": "some environment",
  "cookbook_versions": {
...snip...
    "seven_zip": "= 2.0.2",
    "windows": "= 1.39.1",
    "zookeeper": "= 9.0.1"
  },
  "json_class": "Chef::Environment",
  "chef_type": "environment",
  "default_attributes": {
    "blah": {
      "_template": { "elb_logs_index_template": { "settings": { "number_of_shards": 6 } } }
    }
  },
  "override_attributes": {}
}

the expected output is:

{
  "name": "foo",
  "description": "some environment",
  "cookbook_versions": {
...snip...
    "seven_zip": "= 2.0.2",
    "windows": "= 1.39.1",
    "zookeeper": "= 9.0.1"
  },
  "json_class": "Chef::Environment",
  "chef_type": "environment",
  "default_attributes": {
    "blah": {
      "_template": {
        "elb_logs_index_template": {
          "settings": {
            "number_of_shards": 6
          }
        }
      }
    }
  },
  "override_attributes": {}
}
Phrogz commented 2 years ago

This is an expected feature, depending on your wrapping width. The default is 80, for which that last value fits on one line. If you want to force it to always wrap, use wrap:true, or a smaller width. For example:

require 'neatjson'
h = {a:{b:{c:{d:{e:{f:"deep"}}}}}}
JSON.neat_generate(h, after_colon:1, padding:1)

puts JSON.neat_generate(h, after_colon:1, padding:1)
#=> { "a": { "b": { "c": { "d": { "e": { "f": "deep" } } } } } }

puts JSON.neat_generate(h, after_colon:1, padding:1, wrap:40)
#=> {
#=>   "a": {
#=>     "b": {
#=>       "c": { "d": { "e": { "f": "deep" } } }
#=>     }
#=>   }
#=> }

puts JSON.neat_generate(h, after_colon:1, padding:1, wrap:30)
#=> {
#=>   "a": {
#=>     "b": {
#=>       "c": {
#=>         "d": {
#=>           "e": { "f": "deep" }
#=>         }
#=>       }
#=>     }
#=>   }
#=> }
puts JSON.neat_generate(h, after_colon:1, padding:1, wrap:true)
#=> {
#=>   "a": {
#=>     "b": {
#=>       "c": {
#=>         "d": {
#=>           "e": {
#=>             "f": "deep"
#=>           }
#=>         }
#=>       }
#=>     }
#=>   }
#=> }