public
Last active

[Clojure] code-to-json

  • Download Gist
gistfile1.clj
Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
; Context:
; http://stackoverflow.com/questions/3436216/how-to-map-clojure-code-to-and-from-json
 
(defn escape-string [x]
(clojure.string/replace x #"^[':\\]" "\\\\$0"))
 
(defn code-to-json [x]
(condp #(%1 %2) x
number? x
symbol? (str \' (name x))
keyword? (str \: (name x))
string? (escape-string x)
list? (into [] (cons "list" (map code-to-json x)))
vector? (into [] (cons "vector" (map code-to-json x)))
set? (into [] (cons "set" (map code-to-json x)))
map? (into {} (map #(mapv code-to-json %) x))
(throw (Exception. (format "Unsupported type: %s" (type x))))))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.