Skip to content

Commit

Permalink
c.c.json: add pretty printing
Browse files Browse the repository at this point in the history
  • Loading branch information
Stuart Sierra committed Feb 10, 2010
1 parent 724e767 commit 319057d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/main/clojure/clojure/contrib/json.clj
Expand Up @@ -273,7 +273,7 @@
(defn- write-json-generic [x out]
(if (.isArray (class x))
(write-json (seq x) out)
(throw (Exception. "Don't know how to write JSON of " (class x)))))
(throw (Exception. (str "Don't know how to write JSON of " (class x))))))

(extend nil Write-JSON
{:write-json write-json-null})
Expand Down Expand Up @@ -310,3 +310,32 @@
"Write JSON-formatted output to *out*"
[x]
(write-json x *out*))


;;; JSON PRETTY-PRINTER

;; Based on code by Tom Faulhaber

(defn- pprint-json-array [s]
((formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>") s))

(defn- pprint-json-object [m]
((formatter-out "~<{~;~@{~<~w:~_~w~:>~^, ~_~}~;}~:>")
(for [[k v] m] [(as-str k) v])))

(defn- pprint-json-generic [x]
(if (.isArray (class x))
(pprint-json-array (seq x))
(print (json-str x))))

(defn- pprint-json-dispatch [x]
(cond (nil? x) (print "null")
(instance? java.util.Map x) (pprint-json-object x)
(instance? java.util.Collection x) (pprint-json-array x)
(instance? clojure.lang.ISeq x) (pprint-json-array x)
:else (pprint-json-generic x)))

(defn pprint-json
"Pretty-prints JSON representation of x to *out*"
[x]
(write x :dispatch pprint-json-dispatch))
6 changes: 6 additions & 0 deletions src/test/clojure/clojure/contrib/test_json.clj
Expand Up @@ -170,3 +170,9 @@

(deftest characters-in-symbols-are-escaped
(is (= "\"foo\\u1b1b\"" (json-str (symbol "foo\u1b1b")))))

;;; Pretty-printer

(deftest pretty-printing
(let [x (read-json *pass1-string* false)]
(is (= x (read-json (with-out-str (pprint-json x)) false)))))

0 comments on commit 319057d

Please sign in to comment.