I need to save clojure maps to a file and read them back later to process them.
This is what I could come up with. Is there a better way to accomplish the same thing?
It is easiest to read a single form to and from the file, so I usually put my data into a vector.
I also prefer to use pr or pr-str
rather than print because it is guaranteed to produce readable data,
(def my-data [{:a "foo" :b [1 2 3]} "asdf" 42 #{1 2 3}])
(spit "/tmp/data.edn" (with-out-str (pr my-data)))
nil
(read-string (slurp "/tmp/data.edn"))
[{:a "foo", :b [1 2 3]} "asdf" 42 #{1 2 3}]
vs:
(spit "/tmp/data.edn" (with-out-str (print my-data)))
(read-string (slurp "/tmp/data.edn"))
[{:a foo, :b [1 2 3]} asdf 42 #{1 2 3}]
notice how the string `"asdf" was read back as a symbol.
.toString
also works fine:
(spit "/tmp/data.edn" (.toString my-data))
(read-string (slurp "/tmp/data.edn"))
[{:a "foo", :b [1 2 3]} "asdf" 42 #{1 2 3}]