Created
January 28, 2009 18:44
-
-
Save wilkes/54117 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(ns rabscuttle.test-json | |
(:require [rabscuttle.json :as json]) | |
(:use [clojure.contrib.test-is])) | |
(deftest encode-value | |
(let [pairs [["string" "\"string\""] | |
["" "\"\""] | |
["\"" "\"\"\""] | |
[:keyword "\"keyword\""] | |
['symbol "\"symbol\""] | |
[true "true"] | |
[false "false"] | |
[nil "null"] | |
[1 "1"] | |
[1.1 "1.1"] | |
[1/2 "0.5"] | |
[[1 "string"] "[1,\"string\"]"] | |
[{"foo" 1 "bar" 1/2} "{\"foo\":1,\"bar\":0.5}"]]] | |
(doseq [[value expected-result] pairs] | |
(is (= expected-result (json/encode value)))))) |
This file contains hidden or 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
(ns rabscuttle.json) | |
(defmulti encode class) | |
(defn encode-pairs [pairs] | |
(map (fn [[key val]] | |
(let [k (if (keyword? key) | |
(name key) | |
(str key))] | |
(str "\"" k "\":" (encode val)))) | |
pairs)) | |
(defmethod encode String [x] | |
(str "\"" x "\"")) | |
(defmethod encode clojure.lang.Named [x] | |
(encode (name x))) | |
(defmethod encode Boolean [x] | |
(str x)) | |
(defmethod encode nil [x] | |
"null") | |
(defmethod encode clojure.lang.Ratio [x] | |
(str (* 1.0 x))) | |
(defmethod encode Number [x] | |
(str x)) | |
(defmethod encode java.util.List [x] | |
(str "[" (reduce str (interpose "," (map encode x))) "]")) | |
(defmethod encode java.util.Map [x] | |
(str "{" (reduce str (interpose "," (encode-pairs x))) "}")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment