Ash
Ash

Reputation: 2601

Serialize an input-map into string

I am trying to write a generic serilization function in clojure. Something 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.

Upvotes: 6

Views: 5848

Answers (4)

Tinybit
Tinybit

Reputation: 101

It is quit simple.

(str input-map)

Upvotes: 4

overthink
overthink

Reputation: 24443

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 :)

Upvotes: 5

Julien Chastang
Julien Chastang

Reputation: 17774

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

Upvotes: 7

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17773

"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.

Upvotes: 1

Related Questions