我怎样才能在Clojure中将PersistentHashMap打印成字符串?

时间:2010-12-29 15:44:14

标签: clojure

如何在Clojure中将PersistentHashMap打印成字符串?我正在寻找类似的东西:

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

我可以传递给String

4 个答案:

答案 0 :(得分:42)

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

编辑:等效简洁版:

(with-out-str (clojure.pprint/pprint {:a 10 :b 20}))

答案 1 :(得分:16)

这应该有所帮助:

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

根据clojure.pprint / write documentation

  

如果出现以下情况,则返回字符串结果:stream为nil,否则为nil。

答案 2 :(得分:15)

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"

答案 3 :(得分:9)

(pr-str {:a 1 :b 2}) ;; => "{:a 1, :b 2}"