Question

I need to create JSON objects from clojure maps that store things like clojure vars. The base implementation throws this kind of error when it sees them:

java.lang.Exception: Don't know how to write JSON of class clojure.lang.Var

Can anybody point me to sample code on how to extend the capabilities of the JSON writer?

Thanks.

Was it helpful?

Solution

Well, I figured out the answer. There's another SO question that answers it partially: How to map clojure code to and from JSON?

But here's the code that worked for me:

(defn- write-json-clojure-lang-var [x #^PrintWriter out]
(.print out (json-str (str x))))

(extend clojure.lang.Var clojure.contrib.json/Write-JSON
    {:write-json write-json-clojure-lang-var})

Note that all I wanted to do is just render a string version of which Var I'm referring to. You could, of course, do many other things...

OTHER TIPS

An update to the answer from zippy for those of us using the newer clojure.data.json. This is code that will work with the updated/new library:

(defn- write-json-clojure-lang-var [x #^PrintWriter out]
    (.print out (json-str (str x))))

(extend clojure.lang.Var clojure.data.json/JSONWriter
    {:-write write-json-clojure-lang-var})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top