title: How to map clojure code to and from JSON?
body: <p>I have a crazy idea, which involves putting some clojure code into CouchDB and writing views that query it. I don't want to store the clojure code as plain text, because then I would have to worry about parsing it in the views. Formatting and comments don't need to be preserved, but the code should be able to go in and out of the database without changing in structure. Keywords, symbols, and strings should all stay in their native type. Additionally, I want the code to look elegant and be efficient.</p>
  
  <p>I'm thinking of representing things as follows:</p>
  
  <ul>
  <li>Symbols as strings that start with '</li>
  <li>Keywords as strings that start with :</li>
  <li>Strings unmodified, except when they start with ' or :, in which case they're escaped with a backslash.</li>
  <li>(parens) as an array</li>
  <li>[brackets] as an array with "_[]" as the first element</li>
  <li>maps ({}) as an object</li>
  <li>sets (#{}) as an object with the values set to 1 and "_#{}" included.</li>
  </ul>
  
  <p>Critiques, experiences, and ideas are appreciated.</p>
  
  <p><strong>Edit</strong>: Here's what happens if I try reading and writing JSON code using json functions from clojure.contrib:</p>
  
  <pre><code>user&gt; code
  ((ns bz.json.app (:use (ring.middleware file))) (defn hello [req] {:status 200, :headers {"Content-Type" "text/plain"}, :body "Hello World!"}) (def app (wrap-file hello "public")))
  user&gt; (read-json (json-str code))
  [["ns" "bz.json.app" ["use" ["ring.middleware" "file"]]] ["defn" "hello" ["req"] {"body" "Hello World!", "headers" {"Content-Type" "text/plain"}, "status" 200}] ["def" "app" ["wrap-file" "hello" "public"]]]
  </code></pre>
  
  <p>There's a fair bit that needs to be done for line 4 of the above to be exactly like line 2. It appears that it's a library project, unless there's a function somewhere that does it that I don't know about.</p>
  
  <p>With such a library, here's what calling it might look like:</p>
  
  <pre><code>user&gt; (= (json-to-code (read-json (json-str (code-to-json code)))) code)
  true
  </code></pre>