Is there a JSON.stringify(x, null, 2) for pr-str

I used https://github.com/brandonbloom/fipp/ before, but it’s too large library. I want some function like that in debugging. I tried cljs-devtools too, however it’s too heavy to use.

Is there a light-weight solution I can use?

What does JSON.stringify(x, null, 2) do?

=>> node
> a = {a: {b: {c: {d: 1}}}}
{ a: { b: { c: [Object] } } }
> JSON.stringify(a)
'{"a":{"b":{"c":{"d":1}}}}'
> JSON.stringify(a,null,2)
'{\n  "a": {\n    "b": {\n      "c": {\n        "d": 1\n      }\n    }\n  }\n}'
> console.log(JSON.stringify(a))
{"a":{"b":{"c":{"d":1}}}}
undefined
> console.log(JSON.stringify(a,null,2))
{
  "a": {
    "b": {
      "c": {
        "d": 1
      }
    }
  }
}
undefined

Should I say “pretty print”?

Yes, pretty printing is what that is called.

There’s clojure.pprint/pprint. It writes directly to *out*, so if you want the result as a string you can use with-out-str


(require 'clojure.prrint)

(clojure.pprint/pprint {:a {:b {:c {:d (range 20)} :e (range 20)}}}) 
{:a
 {:b
  {:c {:d (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)},
   :e (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)}}}

(with-out-str (clojure.pprint/pprint {:a {:b {:c {:d (range 20)} :e (range 20)}}}))
"{:a\n {:b\n  {:c {:d (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)},\n   :e (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)}}}\n"

Note that it only indents things when they get too long, so your example will not work the same way

(clojure.pprint/pprint {:a {:b {:c {:d 1}}}})
;;=> {:a {:b {:c {:d 1}}}}

I knew that API, but don’t know how to use it in bundled ClojureScript code?

The exact same way you would in Clojure AFAIK. In ClojureScript
clojure.pprint is an alias for cljs.pprint.

1 Like

Wait, I found cljs.pprint/pprint does not generate indentations. But I want indentations!

As a side note, but fipp is faster than cljs.pprint so I’d stick with it if code needs performance. See also this planck post.

It’s quite fast. But also note that it slower compiled to pr-str, which does not add line breaks and indentations, way slower.