Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pretty print a PersistentHashMap in Clojure to a string?

Tags:

clojure

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

like image 864
yazz.com Avatar asked Dec 29 '10 15:12

yazz.com


4 Answers

(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}))
like image 107
Shantanu Kumar Avatar answered Sep 29 '22 09:09

Shantanu Kumar


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.

like image 39
smaant Avatar answered Sep 29 '22 10:09

smaant


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"
like image 33
Abhinav Sarkar Avatar answered Sep 29 '22 09:09

Abhinav Sarkar


(pr-str {:a 1 :b 2}) ;; => "{:a 1, :b 2}"
like image 40
mtyaka Avatar answered Sep 29 '22 10:09

mtyaka