clojure/data.json — pull request #12 by tonsky (2014-01-16 18:08:04+00:00)
Title: Fast way to print indented json

Hi!

`pprint-json` is dead slow because it tries to fit lines within some length. In practice it takes 20–100 times more time to use `pprint-json` instead of `write-str`, up to the point where it just cannot be used in production:

clojure.data.json=> (def data (read-string (slurp "sample.edn")))
#'clojure.data.json/data
clojure.data.json=> (count data)
4613
clojure.data.json=> (time (do (clojure.data.json/write-str data) nil))
"Elapsed time: 219.33 msecs"
clojure.data.json=> (time (do (with-out-str (clojure.data.json/pprint-json data)) nil))
"Elapsed time: 25271.549 msecs"

On the other hand, it’s often very handy to see serialized json at which you can look at with a naked eye.

Solution is very simple: just use indentation when printing array and object elements. It’s very fast and straightforward, yet it dramatically changes human ability to look at such JSON. Structure is evident, the only downside being possibility of very long lines.

I modified write-array and write-object, added new `:indent` option to write, and also fixed `(seq m)` thing in write-object (should be `(seq x)`). There’s some performance penalty, of course, but relatively small:

clojure.data.json=> (time (do (clojure.data.json/write-str data :indent true) nil))
"Elapsed time: 250.18 msecs"