[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Chicken-users] Why does the JSON egg map JSON structs to Scheme vectors
From: |
Vok Vojwo |
Subject: |
[Chicken-users] Why does the JSON egg map JSON structs to Scheme vectors instead of alists? |
Date: |
Sun, 27 Nov 2011 14:16:38 +0100 |
I am a bit confused by the way the JSON egg maps JSON structures to
Scheme values. The JSON egg maps a structure to a vector:
(use json)
(with-input-from-string "{\"pi\":3.14,\"e\":2.71}" json-read)
;; => #(("pi" . 3.14) ("e" . 2.71))
This makes it impossible to use the standard Scheme function assoc to
read the data.
The following functions fix the problem:
(define (json->alist arg)
(cond
((vector? arg)
(map (lambda (pair)
(cons (car pair) (json->alist (cdr pair))))
(vector->list arg)))
((list? arg)
(list->vector (map json->alist arg)))
(else arg)))
(define (alist->json arg)
(cond
((list? arg)
(list->vector (map (lambda (pair)
(cons (car pair) (alist->json (cdr pair))))
arg)))
((vector? arg)
(map alist->json (vector->list arg)))
(else arg)))
A small verification test:
(use http-client)
(define (with-input-from-url url chunk)
(with-input-from-request url #f chunk))
(define json
(with-input-from-url
"http://www.google.com/calendar/feeds/address@hidden/public/full?alt=json"
json-read))
(equal? json (alist->json (json->alist json)))
;; => #t
By using alists it is possible to use assoc to access the data:
(define (assoc* alist . path)
(let assoc* ((path path)
(alist alist))
(if (null? path)
alist
(assoc* (cdr path)
(cdr (assoc (car path) alist))))))
(assoc* (json->alist json) "feed" "title" "$t")
;; => "Official Google External Developer Events"
Is there any reason why the JSON egg creates vectors of pairs?
If not I would suggest to fix it to make it more schemish.