开发者

Serialize an input-map into string

I am trying to write a generic serilization function in clojure. Somethi开发者_高级运维ng Like this

(def input-map {:Name "Ashwani" :Title "Dev"})
(defn serialize [input-map delimiter]
...rest of the code
)

Which when called

(serialize input-map ",") Produces 
Ashwani,Dev

I have some thing as of now which needs specific keys of the map but does this

(defn serialize [input-map]
  (map #(str (% :Name) "," (% :Title) "\n") input-map ) )

What I want to avoid is the hardcoding Name and title there. There must be some way to use reflection or something to accomplish this but unfortunately I dont know enough clojure to get this done.


(defn serialize [m sep] (apply str (concat (interpose sep (vals m)) ["\n"])))


Give this a shot:

(require 'clojure.string)
(defn serialize [m sep] (str (clojure.string/join sep (map (fn [[_ v]] v) m)) "\n"))
(def input-map {:Name "Ashwani" :Title "Dev"})
(serialize input-map ",")

yields

"Ashwani,Dev\n"

Not sure how idiomatic this is, but it should work for you.

Update: Julien's answer is way nicer than mine! vals ... how could I miss that :)


It is quit simple.

(str input-map)


"Normal" clojure types can be serialized using pr-str and re-instated using read-string. Unless you've got a reason to format your serialized data in the specific way you described, I'd suggest using pr-str instead if only because its output is more readable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜