1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
|
;;; json/write.clj: JavaScript Object Notation (JSON) generator
;; by Stuart Sierra, http://stuartsierra.com/
;; May 9, 2009
;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns
#^{:author "Stuart Sierra",
:doc "JavaScript Object Notation (JSON) generator.
This is a low-level implementation of JSON. It supports basic types,
arrays, Collections, and Maps. You can extend it to handle new types
by adding methods to print-json.
This library does NOT attempt to preserve round-trip equality between
JSON and Clojure data types. That is, if you write a JSON string with
this library, then read it back with clojure.contrib.json.read, you
won't necessarily get the exact same data structure.
If you want round-trip equality and/or indented output, try Dan
Larkin's clojure-json library at
http://github.com/danlarkin/clojure-json
This implementation attempts to follow the description of JSON at
<http://json.org/>. Maps become JSON objects, all other collections
become JSON arrays. JSON object keys are always converted to strings.
Within strings, all non-ASCII characters are hexadecimal escaped.
",
:see-also [["http://json.org/", "JSON Home Page"]]}
clojure.contrib.json.write
(:require [clojure.contrib.java-utils :as j])
(:use [clojure.contrib.test-is :only (deftest- is)]))
(defmulti
#^{:doc "Prints x as JSON. Nil becomes JSON null. Keywords become
strings, without the leading colon. Maps become JSON objects, all
other collection types become JSON arrays. Java arrays become JSON
arrays. Unicode characters in strings are escaped as \\uXXXX.
Numbers print as with pr."
:arglists '([x])}
print-json (fn [x] (cond
(nil? x) nil ;; prevent NullPointerException on next line
(.isArray (class x)) ::array
:else (type x))))
;; Primitive types can be printed with Clojure's pr function.
(derive java.lang.Boolean ::pr)
(derive java.lang.Byte ::pr)
(derive java.lang.Short ::pr)
(derive java.lang.Integer ::pr)
(derive java.lang.Long ::pr)
(derive java.lang.Float ::pr)
(derive java.lang.Double ::pr)
;; Collection types can be printed as JSON objects or arrays.
(derive java.util.Map ::object)
(derive java.util.Collection ::array)
;; Symbols and keywords are converted to strings.
(derive clojure.lang.Symbol ::symbol)
(derive clojure.lang.Keyword ::symbol)
(defmethod print-json ::pr [x] (pr x))
(defmethod print-json nil [x] (print "null"))
(defmethod print-json ::symbol [x] (pr (name x)))
(defmethod print-json ::array [s]
(print \[)
(loop [x s]
(when-let [fst (first x)]
(print-json fst)
(when-let [nxt (next x)]
(print \,)
(recur nxt))))
(print \]))
(defmethod print-json ::object [m]
(print \{)
(loop [x m]
(when (first x)
(let [[k v] (first x)]
(print-json (j/as-str k))
(print \:)
(print-json v))
(when (next x)
(print \,)
(recur (next x)))))
(print \}))
(defmethod print-json java.lang.CharSequence [s]
(print \")
(dotimes [i (count s)]
(let [cp (Character/codePointAt s i)]
(cond
;; Handle printable JSON escapes before ASCII
(= cp 34) (print "\\\"")
(= cp 92) (print "\\\\")
(= cp 47) (print "\\/")
;; Print simple ASCII characters
(< 31 cp 127) (print (.charAt s i))
;; Handle non-printable JSON escapes
(= cp 8) (print "\\b")
(= cp 12) (print "\\f")
(= cp 10) (print "\\n")
(= cp 13) (print "\\r")
(= cp 9) (print "\\t")
;; Any other character is printed as Hexadecimal escape
:else (printf "\\u%04x" cp))))
(print \"))
(defn json-str
"Converts x to a JSON-formatted string."
[x]
(with-out-str (print-json x)))
;;; TESTS
;; Run these tests with
;; (clojure.contrib.test-is/run-tests 'clojure.contrib.print-json)
;; Bind clojure.contrib.test-is/*load-tests* to false to omit these
;; tests from production code.
(deftest- can-print-json-strings
(is (= "\"Hello, World!\"" (json-str "Hello, World!")))
(is (= "\"\\\"Embedded\\\" Quotes\"" (json-str "\"Embedded\" Quotes"))))
(deftest- can-print-unicode
(is (= "\"\\u1234\\u4567\"" (json-str "\u1234\u4567"))))
(deftest- can-print-json-null
(is (= "null" (json-str nil))))
(deftest- can-print-json-arrays
(is (= "[1,2,3]" (json-str [1 2 3])))
(is (= "[1,2,3]" (json-str (list 1 2 3))))
(is (= "[1,2,3]" (json-str (sorted-set 1 2 3))))
(is (= "[1,2,3]" (json-str (seq [1 2 3])))))
(deftest- can-print-java-arrays
(is (= "[1,2,3]" (json-str (into-array [1 2 3])))))
(deftest- can-print-empty-arrays
(is (= "[]" (json-str [])))
(is (= "[]" (json-str (list))))
(is (= "[]" (json-str #{}))))
(deftest- can-print-json-objects
(is (= "{\"a\":1,\"b\":2}" (json-str (sorted-map :a 1 :b 2)))))
(deftest- object-keys-must-be-strings
(is (= "{\"1\":1,\"2\":2") (json-str (sorted-map 1 1 2 2))))
(deftest- can-print-empty-objects
(is (= "{}" (json-str {}))))
|