Skip to content

Instantly share code, notes, and snippets.

@dhess
Created January 26, 2009 03:18
Show Gist options
  • Save dhess/52681 to your computer and use it in GitHub Desktop.
Save dhess/52681 to your computer and use it in GitHub Desktop.
Convert vectors in Chicken Scheme json egg output to alists.
;;; The Chicken Scheme json egg provides 2 procedures: json-write and
;;; json-read. json-read represents JSON arrays as Scheme lists and
;;; JSON objects as Scheme vectors, specifically as a vector of dotted
;;; pairs. I like the representation of arrays as lists, but I think
;;; that Scheme association lists (alists) are a better match for JSON
;;; objects, since the latter are a mapping of names to values.
;;;
;;; The following procedure takes the Scheme representation produced by
;;; json-read and converts it to a representation with identical
;;; structure, except that vectors in the json-read representation are
;;; replaced with lists. (Lists and pairs in the json-read
;;; representation are preserved.) This transformation effectively
;;; converts vectors in the json-read representation to alists.
;;;
;;; Example:
;;; (with-input-from-string "[{\"hello\":100,\"hi\":5}, {\"lst\":[1, 2, 3]}]" json-read)
;;;
;;; produces
;;;
;;; (#(("hello" . 100) ("hi" . 5)) #(("lst" 1 2 3)))
;;;
;;; But
;;;
;;; (json-read-fixup (with-input-from-string "[{\"hello\":100,\"hi\":5}, {\"lst\":[1, 2, 3]}]" json-read))
;;;
;;; evaluates to
;;;
;;; ((("hello" . 100) ("hi" . 5)) (("lst" 1 2 3)))
;;;
;;; Note: the json egg can be found here:
;;; http://www.call-with-current-continuation.org/eggs/json.html
(define (json-read-fixup jro)
(cond ((null? jro) jro)
((vector? jro) (json-read-fixup (vector->list jro)))
((pair? jro) (cons (json-read-fixup (car jro))
(json-read-fixup (cdr jro))))
(else jro)))
;;; Here's a 2nd version that converts vectors in the json-read
;;; representation to hash tables instead of alists. The advantage of
;;; this procedure compared to the first (besides the possible
;;; performance benefit of hash tables versus alists) is that its
;;; output can be passed directly to the json egg's json-write
;;; procedure, since json-write converts both hash lists and vectors
;;; of dotted pairs (but not alists) to JSON objects.
(define (json-read-fixup2 jro)
(cond ((null? jro) jro)
((vector? jro)
(alist->hash-table (json-read-fixup2 (vector->list jro))))
((pair? jro)
(cons (json-read-fixup2 (car jro))
(json-read-fixup2 (cdr jro))))
(else jro)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment