문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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})
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top