Skip to content

Commit

Permalink
DJSON-50 Allow user to pass PushbackReader to read for repeated read …
Browse files Browse the repository at this point in the history
…on the same reader

Signed-off-by: Alex Miller <alex.miller@cognitect.com>
  • Loading branch information
puredanger committed Dec 20, 2023
1 parent 3fa0d0a commit c8e4156
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/main/clojure/clojure/data/json.clj
Original file line number Diff line number Diff line change
Expand Up @@ -367,8 +367,12 @@
:key-fn nil
:value-fn nil})
(defn read
"Reads a single item of JSON data from a java.io.Reader. Options are
key-value pairs, valid options are:
"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
Expand Down Expand Up @@ -403,10 +407,13 @@
collections."
[reader & {:as options}]
(let [{:keys [eof-error? eof-value]
:or {eof-error? true}} options]
:or {eof-error? true}} options
pbr (if (instance? PushbackReader reader)
reader
(PushbackReader. reader 64))]
(->> options
(merge default-read-options)
(-read (PushbackReader. reader 64) eof-error? eof-value))))
(-read pbr eof-error? eof-value))))

(defn read-str
"Reads one JSON value from input String. Options are the same as for
Expand Down
14 changes: 14 additions & 0 deletions src/test/clojure/clojure/data/json_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@
(let [s (java.io.PushbackReader. (java.io.StringReader. "42"))]
(is (= 42 (json/read s)))))

;; DJSON-50 - pass PBR to safely do reapeated read
(deftest read-multiple
(let [st "{\"foo\":\"some string\"}{\"foo\":\"another string\"}"
srdr (java.io.StringReader. st)
pbr (java.io.PushbackReader. srdr 64)]
(is (= {"foo" "some string"} (json/read pbr)))
(is (= {"foo" "another string"} (json/read pbr))))

(let [st "{\"foo\":\"some string\"}{\"foo\":\"another long ......................................................... string\"}"
srdr (java.io.StringReader. st)
pbr (java.io.PushbackReader. srdr 64)]
(is (= {"foo" "some string"} (json/read pbr)))
(is (= {"foo" "another long ......................................................... string"} (json/read pbr)))))

(deftest read-from-reader
(let [s (java.io.StringReader. "42")]
(is (= 42 (json/read s)))))
Expand Down

0 comments on commit c8e4156

Please sign in to comment.