-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathjson.clj
More file actions
946 lines (819 loc) · 33.2 KB
/
Copy pathjson.clj
File metadata and controls
946 lines (819 loc) · 33.2 KB
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
;; Copyright (c) Stuart Sierra, 2012. 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) parser/generator.
See http://www.json.org/"}
clojure.data.json
(:refer-clojure :exclude (read))
(:require [clojure.pprint :as pprint])
(:import (java.io PrintWriter PushbackReader StringWriter
Writer StringReader EOFException)))
;; CUSTOM PUSHBACK READER
(set! *warn-on-reflection* true)
(definterface InternalPBR
(^int readChar [])
(^long readChars [^chars buffer ^long start ^long bufflen])
(^void unreadChar [^int c])
(^void unreadChars [^chars buffer ^int off ^int bufflen])
(^java.io.Reader toReader []))
(deftype ReaderPBR [^PushbackReader rdr]
InternalPBR
(readChar [_]
(.read rdr))
(readChars [_ buffer start bufflen]
(.read rdr ^chars buffer start bufflen))
(unreadChar [_ c]
(.unread rdr c))
(unreadChars [_ buffer start bufflen]
(.unread rdr buffer start bufflen))
(toReader [_]
rdr))
(comment
(compile 'clojure.data.json)
)
(deftype StringPBR [^String s ^:unsynchronized-mutable ^long pos ^long len]
InternalPBR
(readChar [_]
(if (< pos len)
(let [p pos]
(set! pos (unchecked-inc pos))
(let [c (int (.charAt s p))]
c))
(let [i (int -1)]
i)))
(readChars [_ buffer start bufflen]
(let [remaining (- len pos)
n (Math/min remaining bufflen)]
(when (pos? n)
(let [p pos
end (+ p n)]
(set! pos end)
(.getChars ^String s p end ^chars buffer start)))
(if (pos? n) n -1)))
(unreadChar [_ _c]
(set! pos (unchecked-dec pos))
nil)
(unreadChars [_ _buffer _start bufflen]
(set! pos (unchecked-subtract pos bufflen))
nil)
(toReader [_]
(StringReader. (.subSequence s pos len))))
(defn- pushback-pbr
[^PushbackReader r]
(->ReaderPBR r))
(defn- string-pbr
[^String s]
(->StringPBR s 0 (.length s)))
;;; JSON READER
(set! *warn-on-reflection* true)
(defn- default-write-key-fn
[x]
(cond (instance? clojure.lang.Named x)
(name x)
(nil? x)
(throw (Exception. "JSON object properties may not be nil"))
:else (str x)))
(defn- default-value-fn [k v] v)
(declare -read)
(defmacro ^:private codepoint [c]
(int c))
(defn- codepoint-clause [[test result]]
(cond (list? test)
[(map int test) result]
(= test :whitespace)
['(9 10 13 32) result]
(= test :js-separators)
['(16r2028 16r2029) result]
:else
[(int test) result]))
(defmacro ^:private codepoint-case [e & clauses]
`(case ~e
~@(mapcat codepoint-clause (partition 2 clauses))
~@(when (odd? (count clauses))
[(last clauses)])))
(defn- read-hex-char [^InternalPBR stream]
;; Expects to be called with the head of the stream AFTER the
;; initial "\u". Reads the next four characters from the stream.
(let [a (.readChar stream)
b (.readChar stream)
c (.readChar stream)
d (.readChar stream)]
(when (or (neg? a) (neg? b) (neg? c) (neg? d))
(throw (EOFException.
"JSON error (end-of-file inside Unicode character escape)")))
(let [s (str (char a) (char b) (char c) (char d))]
(char (Integer/parseInt s 16)))))
(defn- read-escaped-char [^InternalPBR stream]
;; Expects to be called with the head of the stream AFTER the
;; initial backslash.
(let [c (.readChar stream)]
(when (neg? c)
(throw (EOFException. "JSON error (end-of-file inside escaped char)")))
(codepoint-case c
(\" \\ \/) (char c)
\b \backspace
\f \formfeed
\n \newline
\r \return
\t \tab
\u (read-hex-char stream))))
(defn- slow-read-string [^InternalPBR stream ^String already-read]
(let [buffer (StringBuilder. already-read)]
(loop []
(let [c (.readChar stream)]
(when (neg? c)
(throw (EOFException. "JSON error (end-of-file inside string)")))
(codepoint-case c
\" (str buffer)
\\ (do (.append buffer (read-escaped-char stream))
(recur))
(do (.append buffer (char c))
(recur)))))))
(defn- read-quoted-string [^InternalPBR stream]
;; Expects to be called with the head of the stream AFTER the
;; opening quotation mark.
(let [buffer ^chars (char-array 64)
read (.readChars stream buffer 0 64)
end-index (unchecked-dec-int read)]
(when (neg? read)
(throw (EOFException. "JSON error (end-of-file inside string)")))
(loop [i (int 0)]
(let [c (int (aget buffer i))]
(codepoint-case c
\" (let [off (unchecked-inc-int i)
len (unchecked-subtract-int read off)]
(.unreadChars stream buffer off len)
(String. buffer 0 i))
\\ (let [off i
len (unchecked-subtract-int read off)]
(.unreadChars stream buffer off len)
(slow-read-string stream (String. buffer 0 i)))
(if (= i end-index)
(do (.unreadChar stream c)
(slow-read-string stream (String. buffer 0 i)))
(recur (unchecked-inc-int i))))))))
(defn- read-integer [^String string]
(if (< (count string) 18) ; definitely fits in a Long
(Long/valueOf string)
(or (try (Long/valueOf string)
(catch NumberFormatException e nil))
(bigint string))))
(defn- read-decimal [^String string bigdec?]
(if bigdec?
(bigdec string)
(Double/valueOf string)))
(defn- read-number [^InternalPBR stream bigdec?]
(let [buffer (StringBuilder.)
decimal? (loop [stage :minus]
(let [c (.readChar stream)]
(case stage
:minus
(codepoint-case c
\-
(do (.append buffer (char c))
(recur :int-zero))
\0
(do (.append buffer (char c))
(recur :frac-point))
(\1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.append buffer (char c))
(recur :int-digit))
(throw (Exception. "JSON error (invalid number literal)")))
;; Number must either be a single 0 or 1-9 followed by 0-9
:int-zero
(codepoint-case c
\0
(do (.append buffer (char c))
(recur :frac-point))
(\1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.append buffer (char c))
(recur :int-digit))
(throw (Exception. "JSON error (invalid number literal)")))
;; at this point, there is at least one digit
:int-digit
(codepoint-case c
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.append buffer (char c))
(recur :int-digit))
\.
(do (.append buffer (char c))
(recur :frac-first))
(\e \E)
(do (.append buffer (char c))
(recur :exp-symbol))
;; early exit
:whitespace
(do (.unreadChar stream c)
false)
(\, \] \} -1)
(do (.unreadChar stream c)
false)
(throw (Exception. "JSON error (invalid number literal)")))
;; previous character is a "0"
:frac-point
(codepoint-case c
\.
(do (.append buffer (char c))
(recur :frac-first))
(\e \E)
(do (.append buffer (char c))
(recur :exp-symbol))
;; early exit
:whitespace
(do (.unreadChar stream c)
false)
(\, \] \} -1)
(do (.unreadChar stream c)
false)
;; Disallow zero-padded numbers or invalid characters
(throw (Exception. "JSON error (invalid number literal)")))
;; previous character is a "."
:frac-first
(codepoint-case c
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.append buffer (char c))
(recur :frac-digit))
(throw (Exception. "JSON error (invalid number literal)")))
;; any number of following digits
:frac-digit
(codepoint-case c
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.append buffer (char c))
(recur :frac-digit))
(\e \E)
(do (.append buffer (char c))
(recur :exp-symbol))
;; early exit
:whitespace
(do (.unreadChar stream c)
true)
(\, \] \} -1)
(do (.unreadChar stream c)
true)
(throw (Exception. "JSON error (invalid number literal)")))
;; previous character is a "e" or "E"
:exp-symbol
(codepoint-case c
(\- \+)
(do (.append buffer (char c))
(recur :exp-first))
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.append buffer (char c))
(recur :exp-digit)))
;; previous character is a "-" or "+"
;; must have at least one digit
:exp-first
(codepoint-case c
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.append buffer (char c))
(recur :exp-digit))
(throw (Exception. "JSON error (invalid number literal)")))
;; any number of following digits
:exp-digit
(codepoint-case c
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.append buffer (char c))
(recur :exp-digit))
:whitespace
(do (.unreadChar stream c)
true)
(\, \] \} -1)
(do (.unreadChar stream c)
true)
(throw (Exception. "JSON error (invalid number literal)"))))))]
(if decimal?
(read-decimal (str buffer) bigdec?)
(read-integer (str buffer)))))
(defn- next-token [^InternalPBR stream]
(loop [c (.readChar stream)]
(if (< 32 c)
(int c)
(codepoint-case (int c)
:whitespace (recur (.readChar stream))
-1 -1))))
(defn invalid-array-exception []
(Exception. "JSON error (invalid array)"))
(defn- read-array* [^InternalPBR stream options]
;; Handles all array values after the first.
(loop [result (transient [])]
(let [r (conj! result (-read stream true nil options))]
(codepoint-case (int (next-token stream))
\] (persistent! r)
\, (recur r)
(throw (invalid-array-exception))))))
(defn- read-array [^InternalPBR stream options]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
;; Only handles array value.
(let [c (int (next-token stream))]
(codepoint-case c
\] []
\, (throw (invalid-array-exception))
(do (.unreadChar stream c)
(read-array* stream options)))))
(defn- read-key [^InternalPBR stream]
(let [c (int (next-token stream))]
(if (= c (codepoint \"))
(let [key (read-quoted-string stream)]
(if (= (codepoint \:) (int (next-token stream)))
key
(throw (Exception. "JSON error (missing `:` in object)"))))
(if (= c (codepoint \}))
nil
(throw (Exception. (str "JSON error (non-string key in object), found `" (char c) "`, expected `\"`")))))))
(defn- read-object [^InternalPBR stream options]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
(let [key-fn (get options :key-fn)
value-fn (get options :value-fn)]
(loop [result (transient {})]
(if-let [key (read-key stream)]
(let [key (cond-> key key-fn key-fn)
value (-read stream true nil options)
r (if value-fn
(let [out-value (value-fn key value)]
(if-not (= value-fn out-value)
(assoc! result key out-value)
result))
(assoc! result key value))]
(codepoint-case (int (next-token stream))
\, (recur r)
\} (persistent! r)
(throw (Exception. "JSON error (missing entry in object)"))))
(let [r (persistent! result)]
(if (empty? r)
r
(throw (Exception. "JSON error empty entry in object is not allowed"))))))))
(defn- -read
[^InternalPBR stream eof-error? eof-value options]
(let [c (int (next-token stream))]
(codepoint-case c
;; Read numbers
(\- \0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
(do (.unreadChar stream c)
(read-number stream (:bigdec options)))
;; Read strings
\" (read-quoted-string stream)
;; Read null as nil
\n (if (and (= (codepoint \u) (.readChar stream))
(= (codepoint \l) (.readChar stream))
(= (codepoint \l) (.readChar stream)))
nil
(throw (Exception. "JSON error (expected null)")))
;; Read true
\t (if (and (= (codepoint \r) (.readChar stream))
(= (codepoint \u) (.readChar stream))
(= (codepoint \e) (.readChar stream)))
true
(throw (Exception. "JSON error (expected true)")))
;; Read false
\f (if (and (= (codepoint \a) (.readChar stream))
(= (codepoint \l) (.readChar stream))
(= (codepoint \s) (.readChar stream))
(= (codepoint \e) (.readChar stream)))
false
(throw (Exception. "JSON error (expected false)")))
;; Read JSON objects
\{ (read-object stream options)
;; Read JSON arrays
\[ (read-array stream options)
(if (neg? c) ;; Handle end-of-stream
(if eof-error?
(throw (EOFException. "JSON error (end-of-file)"))
eof-value)
(throw (Exception.
(str "JSON error (unexpected character): " (char c))))))))
(defn- -read1
[^InternalPBR stream eof-error? eof-value options]
(let [val (-read stream eof-error? eof-value options)]
(if-let [extra-data-fn (:extra-data-fn options)]
(if (or eof-error? (not (identical? eof-value val)))
(let [c (.readChar stream)]
(if (neg? c)
val
(do
(.unreadChar stream c)
(extra-data-fn val (.toReader stream)))))
val)
val)))
(defn on-extra-throw
"Pass as :extra-data-fn to `read` or `read-str` to throw if data is found
after the first object."
[val rdr]
(throw (ex-info "Found extra data after json object" {:val val})))
(defn on-extra-throw-remaining
"Pass as :extra-data-fn to `read` or `read-str` to throw if data is found
after the first object and return the remaining data in ex-data :remaining."
[val rdr]
(let [remaining (slurp rdr)]
(throw (ex-info (str "Found extra data after json object: " remaining)
{:val val, :remaining remaining}))))
(def default-read-options {:bigdec false
:key-fn nil
:value-fn nil})
(defn read
"Reads a single item of JSON data from a java.io.Reader.
If you wish to repeatedly read items from the same reader, you must
supply a PushbackReader and reuse it on subsequent calls.
Options are key-value pairs, valid options are:
:eof-error? boolean
If true (default) will throw exception if the stream is empty.
:eof-value Object
Object to return if the stream is empty and eof-error? is
false. Default is nil.
:bigdec boolean
If true use BigDecimal for decimal numbers instead of Double.
Default is false.
:key-fn function
Single-argument function called on JSON property names; return
value will replace the property names in the output. Default
is clojure.core/identity, use clojure.core/keyword to get
keyword properties.
:value-fn function
Function to transform values in maps (\"objects\" in JSON) in
the output. For each JSON property, value-fn is called with
two arguments: the property name (transformed by key-fn) and
the value. The return value of value-fn will replace the value
in the output. If value-fn returns itself, the property will
be omitted from the output. The default value-fn returns the
value unchanged. This option does not apply to non-map
collections.
:extra-data-fn function
If :extra-data-fn is not nil, then the reader will be checked
for extra data after the read. If found, the extra-data-fn will
be invoked with the read value and the reader. The result of
the extra-data-fn will be returned."
[reader & {:as options}]
(let [{:keys [eof-error? eof-value]
:or {eof-error? true}} options
pbr (pushback-pbr
(if (instance? PushbackReader reader)
reader
(PushbackReader. reader 64)))]
(->> options
(merge default-read-options)
(-read1 pbr eof-error? eof-value))))
(defn read-str
"Reads one JSON value from input String. Options are the same as for
read."
[string & {:as options}]
(let [{:keys [eof-error? eof-value]
:or {eof-error? true}} options]
(->> options
(merge default-read-options)
(-read1 (string-pbr string) eof-error? eof-value))))
;;; JSON WRITER
(defprotocol JSONWriter
(-write [object out options]
"Print object to Appendable out as JSON"))
(defn- ->hex-string [^Appendable out cp]
(let [cpl (long cp)]
(.append out "\\u")
(cond
(< cpl 16)
(.append out "000")
(< cpl 256)
(.append out "00")
(< cpl 4096)
(.append out "0"))
(.append out (Integer/toHexString cp))))
(def ^{:tag "[S"} codepoint-decoder
(let [shorts (short-array 128)]
(dotimes [i 128]
(codepoint-case i
\" (aset shorts i (short 1))
\\ (aset shorts i (short 1))
\/ (aset shorts i (short 2))
\backspace (aset shorts i (short 3))
\formfeed (aset shorts i (short 4))
\newline (aset shorts i (short 5))
\return (aset shorts i (short 6))
\tab (aset shorts i (short 7))
(if (< i 32)
(aset shorts i (short 8))
(aset shorts i (short 0)))))
shorts))
(defn- slow-write-string [^CharSequence s ^Appendable out options]
(let [decoder codepoint-decoder]
(dotimes [i (.length s)]
(let [cp (int (.charAt s i))]
(if (< cp 128)
(case (aget decoder cp)
0 (.append out (char cp))
1 (do (.append out (char (codepoint \\))) (.append out (char cp)))
2 (.append out (if (get options :escape-slash) "\\/" "/"))
3 (.append out "\\b")
4 (.append out "\\f")
5 (.append out "\\n")
6 (.append out "\\r")
7 (.append out "\\t")
8 (->hex-string out cp))
(codepoint-case cp
:js-separators (if (get options :escape-js-separators)
(->hex-string out cp)
(.append out (char cp)))
(if (get options :escape-unicode)
(->hex-string out cp) ; Hexadecimal-escaped
(.append out (char cp)))))))))
(defn- write-string [^CharSequence s ^Appendable out options]
(let [decoder codepoint-decoder
l (.length s)]
(.append out \")
(loop [i 0]
(if (= i l)
(.append out s)
(let [cp (int (.charAt s i))]
(if (and (< cp 128)
(zero? (aget decoder cp)))
(recur (unchecked-inc i))
(do
(.append out s 0 i)
(slow-write-string (.subSequence s i l) out options))))))
(.append out \")))
(defn- write-indent [^Appendable out options]
(let [indent-depth (:indent-depth options)]
(.append out \newline)
(loop [i indent-depth]
(when (pos? i)
(.append out " ")
(recur (dec i))))))
(defn- write-object [m ^Appendable out options]
(let [key-fn (get options :key-fn)
value-fn (get options :value-fn)
indent (get options :indent)
opts (cond-> options
indent (update :indent-depth inc))]
(.append out \{)
(when (and indent (seq m))
(write-indent out opts))
(loop [x m, have-printed-kv false]
(when (seq x)
(let [[k v] (first x)
out-key (key-fn k)
out-value (value-fn k v)
nxt (next x)]
(when-not (string? out-key)
(throw (Exception. "JSON object keys must be strings")))
(if-not (= value-fn out-value)
(do
(when have-printed-kv
(.append out \,)
(when indent
(write-indent out opts)))
(write-string out-key out opts)
(.append out \:)
(when indent
(.append out \space))
(-write out-value out opts)
(when (seq nxt)
(recur nxt true)))
(when (seq nxt)
(recur nxt have-printed-kv))))))
(when (and indent (seq m))
(write-indent out options)))
(.append out \}))
(defn- write-array [s ^Appendable out options]
(let [indent (get options :indent)
opts (cond-> options
indent (update :indent-depth inc))]
(.append out \[)
(when (and indent (seq s))
(write-indent out opts))
(loop [x s]
(when (seq x)
(let [fst (first x)
nxt (next x)]
(-write fst out opts)
(when (seq nxt)
(.append out \,)
(when indent
(write-indent out opts))
(recur nxt)))))
(when (and indent (seq s))
(write-indent out options)))
(.append out \]))
(defn- write-bignum [x ^Appendable out options]
(.append out (str x)))
(defn- write-float [^Float x ^Appendable out options]
(cond (.isInfinite x)
(throw (Exception. "JSON error: cannot write infinite Float"))
(.isNaN x)
(throw (Exception. "JSON error: cannot write Float NaN"))
:else
(.append out (str x))))
(defn- write-double [^Double x ^Appendable out options]
(cond (.isInfinite x)
(throw (Exception. "JSON error: cannot write infinite Double"))
(.isNaN x)
(throw (Exception. "JSON error: cannot write Double NaN"))
:else
(.append out (str x))))
(defn- write-plain [x ^Appendable out options]
(.append out (str x)))
(defn- write-uuid [^java.util.UUID x ^Appendable out options]
(.append out \")
(.append out (.toString x))
(.append out \"))
(defn- write-instant [^java.time.Instant x ^Appendable out options]
(let [formatter ^java.time.format.DateTimeFormatter (:date-formatter options)]
(.append out \")
(.append out (.format formatter x))
(.append out \")))
(defn- write-date [^java.util.Date x ^Appendable out options]
(write-instant (.toInstant x) out options))
(defn- default-sql-date->instant-fn [^java.sql.Date d]
(.toInstant (.atStartOfDay (.toLocalDate d) (java.time.ZoneId/systemDefault))))
(defn- write-sql-date [^java.sql.Date x ^Appendable out options]
(let [->instant (:sql-date-converter options)]
(write-instant (->instant x) out options)))
(defn- write-null [x ^Appendable out options]
(.append out "null"))
(defn- write-named [x out options]
(write-string (name x) out options))
(defn- write-generic [x out options]
(if (.isArray (class x))
(-write (seq x) out options)
((:default-write-fn options) x out options)))
(defn- write-ratio [x out options]
(-write (double x) out options))
;; nil, true, false
(extend nil JSONWriter {:-write write-null})
(extend java.lang.Boolean JSONWriter {:-write write-plain})
;; Numbers
(extend java.lang.Byte JSONWriter {:-write write-plain})
(extend java.lang.Short JSONWriter {:-write write-plain})
(extend java.lang.Integer JSONWriter {:-write write-plain})
(extend java.lang.Long JSONWriter {:-write write-plain})
(extend java.lang.Float JSONWriter {:-write write-float})
(extend java.lang.Double JSONWriter {:-write write-double})
(extend clojure.lang.Ratio JSONWriter {:-write write-ratio})
(extend java.math.BigInteger JSONWriter {:-write write-bignum})
(extend java.math.BigDecimal JSONWriter {:-write write-bignum})
(extend java.util.concurrent.atomic.AtomicInteger JSONWriter {:-write write-plain})
(extend java.util.concurrent.atomic.AtomicLong JSONWriter {:-write write-plain})
(extend java.util.UUID JSONWriter {:-write write-uuid})
(extend java.time.Instant JSONWriter {:-write write-instant})
(extend java.util.Date JSONWriter {:-write write-date})
(extend java.sql.Date JSONWriter {:-write write-sql-date})
(extend clojure.lang.BigInt JSONWriter {:-write write-bignum})
;; Symbols, Keywords, and Strings
(extend clojure.lang.Named JSONWriter {:-write write-named})
(extend java.lang.CharSequence JSONWriter {:-write write-string})
;; Collections
(extend java.util.Map JSONWriter {:-write write-object})
(extend java.util.Collection JSONWriter {:-write write-array})
;; Maybe a Java array, otherwise fail
(extend java.lang.Object JSONWriter {:-write write-generic})
(defn- default-write-fn [x out options]
(throw (Exception. (str "Don't know how to write JSON of " (class x)))))
(def default-write-options {:escape-unicode true
:escape-js-separators true
:escape-slash true
:sql-date-converter default-sql-date->instant-fn
:date-formatter java.time.format.DateTimeFormatter/ISO_INSTANT
:key-fn default-write-key-fn
:value-fn default-value-fn
:default-write-fn default-write-fn
:indent false
:indent-depth 0 ;; internal, to track nesting depth
})
(defn write
"Write JSON-formatted output to a java.io.Writer. Options are
key-value pairs, valid options are:
:escape-unicode boolean
If true (default) non-ASCII characters are escaped as \\uXXXX
:escape-js-separators boolean
If true (default) the Unicode characters U+2028 and U+2029 will
be escaped as \\u2028 and \\u2029 even if :escape-unicode is
false. (These two characters are valid in pure JSON but are not
valid in JavaScript strings.)
:escape-slash boolean
If true (default) the slash / is escaped as \\/
:sql-date-converter function
Single-argument function used to convert a java.sql.Date to
a java.time.Instant. As java.sql.Date does not have a
time-component (which is required by java.time.Instant), it needs
to be computed. The default implementation, `default-sql-date->instant-fn`
uses
```
(.toInstant (.atStartOfDay (.toLocalDate sql-date) (java.time.ZoneId/systemDefault)))
```
:date-formatter
A java.time.DateTimeFormatter instance, defaults to DateTimeFormatter/ISO_INSTANT
:key-fn function
Single-argument function called on map keys; return value will
replace the property names in the output. Must return a
string. Default calls clojure.core/name on symbols and
keywords and clojure.core/str on everything else.
:value-fn function
Function to transform values in maps before writing. For each
key-value pair in an input map, called with two arguments: the
key (BEFORE transformation by key-fn) and the value. The
return value of value-fn will replace the value in the output.
If the return value is a number, boolean, string, or nil it
will be included literally in the output. If the return value
is a non-map collection, it will be processed recursively. If
the return value is a map, it will be processed recursively,
calling value-fn again on its key-value pairs. If value-fn
returns itself, the key-value pair will be omitted from the
output. This option does not apply to non-map collections.
:default-write-fn function
Function to handle types which are unknown to data.json. Defaults
to a function which throws an exception. Expects to be called with
three args, the value to be serialized, the output stream, and the
options map.
:indent boolean
If true, indent json while writing (default = false)."
[x ^Writer writer & {:as options}]
(-write x writer (merge default-write-options options)))
(defn write-str
"Converts x to a JSON-formatted string. Options are the same as
write."
^String [x & {:as options}]
(let [sw (StringWriter.)]
(-write x sw (merge default-write-options options))
(.toString sw)))
;;; JSON PRETTY-PRINTER
;; Based on code by Tom Faulhaber
(defn- pprint-array [s]
((pprint/formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>") s))
(defn- pprint-object [m options]
(let [key-fn (:key-fn options)]
((pprint/formatter-out "~<{~;~@{~<~w:~_~w~:>~^, ~_~}~;}~:>")
(for [[k v] m] [(key-fn k) v]))))
(defn- pprint-generic [x options]
(if (.isArray (class x))
(pprint-array (seq x))
;; pprint proxies Writer, so we can't just wrap it
(print (with-out-str (-write x (PrintWriter. *out*) options)))))
(defn- pprint-dispatch [x options]
(cond (nil? x) (print "null")
(instance? java.util.Map x) (pprint-object x options)
(instance? java.util.Collection x) (pprint-array x)
(instance? clojure.lang.ISeq x) (pprint-array x)
:else (pprint-generic x options)))
(defn pprint
"Pretty-prints JSON representation of x to *out*. Options are the same
as for write except :value-fn and :indent, which are not supported."
[x & {:as options}]
(let [opts (merge default-write-options options)]
(pprint/with-pprint-dispatch #(pprint-dispatch % opts)
(pprint/pprint x))))
;; DEPRECATED APIs from 0.1.x
(defn read-json
"DEPRECATED; replaced by read-str.
Reads one JSON value from input String or Reader. If keywordize? is
true (default), object keys will be converted to keywords. If
eof-error? is true (default), empty input will throw an
EOFException; if false EOF will return eof-value."
([input]
(read-json input true true nil))
([input keywordize?]
(read-json input keywordize? true nil))
([input keywordize? eof-error? eof-value]
(let [key-fn (if keywordize? keyword identity)]
(condp instance? input
String
(read-str input
:key-fn key-fn
:eof-error? eof-error?
:eof-value eof-value)
java.io.Reader
(read input
:key-fn key-fn
:eof-error? eof-error?
:eof-value eof-value)))))
(defn write-json
"DEPRECATED; replaced by 'write'.
Print object to PrintWriter out as JSON"
[x out escape-unicode?]
(write x out :escape-unicode escape-unicode?))
(defn json-str
"DEPRECATED; replaced by 'write-str'.
Converts x to a JSON-formatted string.
Valid options are:
:escape-unicode false
to turn of \\uXXXX escapes of Unicode characters."
[x & options]
(apply write-str x options))
(defn print-json
"DEPRECATED; replaced by 'write' to *out*.
Write JSON-formatted output to *out*.
Valid options are:
:escape-unicode false
to turn off \\uXXXX escapes of Unicode characters."
[x & options]
(apply write x *out* options))
(defn pprint-json
"DEPRECATED; replaced by 'pprint'.
Pretty-prints JSON representation of x to *out*.
Valid options are:
:escape-unicode false
to turn off \\uXXXX escapes of Unicode characters."
[x & options]
(apply pprint x options))