How to pretty print JSON to a file in Clojure?
Asked Answered
L

2

11

I would like to store JSON content in files but using the pretty version.

Just to be clear, this is the normal JSON:

{"b":2, "a":1}

This is the pretty version of it:

{
    "b": 2,
    "a": 1
}

Is there a way in Clojure to achieve this?

Librate answered 26/4, 2014 at 6:33 Comment(1)
The pprint function in clojure.data.json looks like what you want. I suppose you can do the write on another thread if diverting *out* is a problem.Daunt
S
9

Use the cheshire library found here and use the generate-string function with the pretty flag set to true

Example

;; generate some JSON with pretty formatting
(generate-string {:foo "bar" :baz {:eggplant [1 2 3]}} {:pretty true})
;; {
;;   "foo" : "bar",
;;   "baz" : {
;;     "eggplant" : [ 1, 2, 3 ]
;;   }
;; }
Skeie answered 26/4, 2014 at 10:57 Comment(1)
Should also consider my solution below if you don't want or need an external library.Bahr
B
9

You can use the built-in with-out-str function to capture anything written to the output buffer and store it as a string.

(with-out-str (clojure.data.json/pprint your-map-or-whatever))
Bahr answered 17/5, 2020 at 13:29 Comment(1)
Is there a way to avoid capturing to an internal string buffer and writing (or spit'ting) straight to a file?Circumcise

© 2022 - 2024 — McMap. All rights reserved.