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

后端 未结 4 1591
情歌与酒
情歌与酒 2021-02-03 20:43

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

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

which

相关标签:
4条回答
  • 2021-02-03 21:10
    (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}))
    
    0 讨论(0)
  • 2021-02-03 21:10
    (pr-str {:a 1 :b 2}) ;; => "{:a 1, :b 2}"
    
    0 讨论(0)
  • 2021-02-03 21:26

    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.

    0 讨论(0)
  • 2021-02-03 21:30
    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"
    
    0 讨论(0)
提交回复
热议问题