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

NeatJSON hangs on complicated document #7

Closed chroche closed 8 years ago

chroche commented 8 years ago

neat_generate() fails on a deeply nested JSON doc that pretty_generate() handles correctly. It gets stuck and never returns. See example script here: neatjson_fails.rb.txt

Phrogz commented 8 years ago

Thank you for the report. I will investigate.

Phrogz commented 8 years ago

Looks like this is a backtracking-style problem when using the (default) wrap option. In order to see if a value can fit on the line, it has to serialize that value; if it can't, it tries to break it apart and try again. This results in deeply-nested object/arrays re-serializing the leaf values a LOT. It doesn't NEVER return…it just takes a really, really long time.

For example, this simple test…

h = {a:{b:{c:{d:{e:{f:{g:{h:{i:{j:{k:{l:{m:"oops"}}}}}}}}}}}}}
JSON.neat_generate(h,wrap:1)

…ends up re-serializing the "oops" over a million times (1,062,882, in fact). Oops.

I tried to let your test case run to completion, but gave up after the "prices.rrp_inc_vat" string had been serialized 70 million times.

I can (and will) fix this for Ruby using simple memoization. However, I'll have to consider how I can do that for JavaScript (where I cannot index an object using an object's internal id).