Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

DJSON-11: Fix printing of unnecessary commas with value-fn

Adds state to loop remembering whether any key/value pairs have been
printed before, to distinguish whether to print a comma or not.

Changes test case to use sorted-map, both for determinism in the
order, and to exhibit the bug with the uncorrected version of
write-object.

Signed-off-by: Stuart Sierra <mail@stuartsierra.com>
  • Loading branch information...
commit 4daaa48e41d0dc1d27e3ceb9d64e46967d31f8b8 1 parent feacd54
@jafingerhut jafingerhut authored stuartsierra committed
View
19 src/main/clojure/clojure/data/json.clj
@@ -307,7 +307,7 @@
(defn- write-object [m ^PrintWriter out]
(.print out \{)
- (loop [x m]
+ (loop [x m, have-printed-kv false]
(when (seq m)
(let [[k v] (first x)
out-key (*key-fn* k)
@@ -315,14 +315,17 @@
nxt (next x)]
(when-not (string? out-key)
(throw (Exception. "JSON object keys must be strings")))
- (when-not (= *value-fn* out-value)
- (write-string out-key out)
- (.print out \:)
- (-write out-value out)
+ (if-not (= *value-fn* out-value)
+ (do
+ (when have-printed-kv
+ (.print out \,))
+ (write-string out-key out)
+ (.print out \:)
+ (-write out-value out)
+ (when (seq nxt)
+ (recur nxt true)))
(when (seq nxt)
- (.print out \,)))
- (when (seq nxt)
- (recur nxt)))))
+ (recur nxt have-printed-kv))))))
(.print out \}))
(defn- write-array [s ^PrintWriter out]
View
2  src/test/clojure/clojure/data/json_test.clj
@@ -112,7 +112,7 @@
thisfn
v)))))
(is (= "{\"c\":1,\"e\":2}"
- (json/write-str {:a nil, :b nil, :c 1, :d nil, :e 2, :f nil}
+ (json/write-str (sorted-map :a nil, :b nil, :c 1, :d nil, :e 2, :f nil)
:value-fn (fn remove-nils [k v]
(if (nil? v)
remove-nils
Please sign in to comment.
Something went wrong with that request. Please try again.