eldoctoro
eldoctoro

Reputation: 893

Printing and reading lists from a file in Clojure

I have a Clojure data structure of the form:

{:foo '("bar" "blat")}

and have tried writing them to a file using the various pr/prn/print. However, each time the structure is written as

{:foo ("bar" "blat")}

then when I try to read in it using load-file, I get an error such as:

java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IF n (build-state.clj:79)

presumably as the list is being evaluated as a function call when it is read. Is there any way to write the structure out with the lists in their quoted form?

thanks, Nick

Upvotes: 4

Views: 323

Answers (1)

Brian Carper
Brian Carper

Reputation: 72926

The inverse of printing is usually reading, not loading.

user> (read-string "{:foo (\"bar\" \"blat\")}")
{:foo ("bar" "blat")}

If you really need to print loadable code, you need to quote it twice.

user> (pr-str '{:foo '("bar" "blat")})
"{:foo (quote (\"bar\" \"blat\"))}"

user> (load-string (pr-str '{:foo '("bar" "blat")}))
{:foo ("bar" "blat")}

Upvotes: 8

Related Questions