Skip to content

Instantly share code, notes, and snippets.

@qerub
Last active April 21, 2021 09:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qerub/3219854 to your computer and use it in GitHub Desktop.
Save qerub/3219854 to your computer and use it in GitHub Desktop.
Representing [Clojure] code in JSON
; 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))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment