Last active
April 21, 2021 09:46
-
-
Save qerub/3219854 to your computer and use it in GitHub Desktop.
Representing [Clojure] code in JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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