Skip to content

Commit

Permalink
json: add parameter to disable sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
fare committed Feb 12, 2021
1 parent ba0a892 commit 2442453
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
8 changes: 6 additions & 2 deletions src/std/text/json-test.ss
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@
(test-suite "test :std/text/json"

(def (check-encode-decode obj str)
(check (call-with-output-string (cut write-json obj <>)) => str)
(check (call-with-input-string str read-json) => obj))
(parameterize ((json-sort-keys #f))
(check (call-with-input-string (call-with-output-string (cut write-json obj <>)) read-json)
=> obj))
(parameterize ((json-sort-keys #t))
(check (call-with-output-string (cut write-json obj <>)) => str)
(check (call-with-input-string str read-json) => obj)))

(def (check-encode-decode= obj)
(let (p (open-output-u8vector))
Expand Down
12 changes: 10 additions & 2 deletions src/std/text/json.ss
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
:std/text/hex)
(export read-json write-json
string->json-object json-object->string
json-symbolic-keys json-list-wrapper
json-symbolic-keys json-list-wrapper json-sort-keys
write-json-alist write-json-alist/sort json-sort-alist)
(declare (not safe))

Expand All @@ -49,6 +49,11 @@
(def json-list-wrapper
(make-parameter identity))

;; Should object keys be sorted when writing json?
;; Checking for duplicate keys only reliably works when this is true.
(def json-sort-keys
(make-parameter #t))

;;; implementation
(def (raise-invalid-token port char)
(if (eof-object? char)
Expand Down Expand Up @@ -370,7 +375,10 @@
(write-json-alist (json-sort-alist alist obj) port obj))

(def (write-json-hash obj port)
(write-json-alist/sort (hash->list obj) port obj))
(def lst (hash->list obj))
(if (json-sort-keys)
(write-json-alist/sort lst port obj)
(write-json-alist lst port obj)))

(def (write-json-string obj port)
(def escape
Expand Down

0 comments on commit 2442453

Please sign in to comment.