34

How can I pretty print a PersistentHashMap in Clojure to a string? I am looking for something like:

(str (pprint {... hash map here...})

which I can pass around as a String

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
yazz.com
  • 57,320
  • 66
  • 234
  • 385

4 Answers4

47
(let [s (java.io.StringWriter.)]
  (binding [*out* s]
    (clojure.pprint/pprint {:a 10 :b 20}))
  (.toString s))

Edit: Equivalent succinct version:

(with-out-str (clojure.pprint/pprint {:a 10 :b 20}))
Shantanu Kumar
  • 1,240
  • 1
  • 12
  • 14
  • 6
    You can also use with-out-str, which cuts out all the binding stuff. – Rayne Dec 29 '10 at 16:04
  • will this work if other threads output to *out*. Is it threadsafe? – yazz.com Dec 29 '10 at 16:15
  • 1
    @Zubair - The binding macro is always thread safe. The new var binding is created on a per thread basis and the root binding is unchanged. See http://clojure.org/vars – Alex Stoddard Dec 29 '10 at 21:28
  • 1
    @Rayne Thanks for mentioning. I could not find with-out-str on clojuredocs in the first pass, but can see it there now. So, the updated solution is this: (with-out-str (clojure.pprint/pprint {:a 10 :b 20})) – Shantanu Kumar Dec 30 '10 at 07:05
  • 1
    Please post this last comment as an answer - it's easy to miss ;) – bluegray Nov 15 '12 at 19:44
  • Convenient macro: (defmacro pprint-str [forms] `(with-out-str (clojure.pprint/pprint (do ~forms)))) – Paul Legato Jun 23 '15 at 21:49
20

This should help:

(clojure.pprint/write {:a 1 :b 2} :stream nil)

according to clojure.pprint/write documentation

Returns the string result if :stream is nil or nil otherwise.

smaant
  • 651
  • 6
  • 4
16
user=> (import java.io.StringWriter)
java.io.StringWriter
user=> (use '[clojure.pprint :only (pprint)])
nil
user=> (defn hashmap-to-string [m] 
  (let [w (StringWriter.)] (pprint m w)(.toString w)))
#'user/hashmap-to-string
user=> (hashmap-to-string {:a 1 :b 2})
"{:a 1, :b 2}\n"
Abhinav Sarkar
  • 23,534
  • 11
  • 81
  • 97
  • The compiler complains "CompilerException java.lang.RuntimeException: Unable to resolve symbol: w in this context". The original post works but Rayne's edits seem to have broken it! – AnnanFay Mar 15 '12 at 11:35
9
(pr-str {:a 1 :b 2}) ;; => "{:a 1, :b 2}"
mtyaka
  • 8,670
  • 1
  • 38
  • 40