From cd7057a886b0ddb2a6c804bd297d07c739456b48 Mon Sep 17 00:00:00 2001 From: Robby Zambito Date: Thu, 16 Feb 2023 00:23:58 -0500 Subject: Add initial implementation of json-records These behave like normal records, but with an added procedure to convert from a JSON string. --- lib/zambyte/meta/chibi.scm | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) (limited to 'lib/zambyte/meta/chibi.scm') diff --git a/lib/zambyte/meta/chibi.scm b/lib/zambyte/meta/chibi.scm index 812694f..7cc777d 100644 --- a/lib/zambyte/meta/chibi.scm +++ b/lib/zambyte/meta/chibi.scm @@ -1,28 +1,51 @@ -(import (chibi json) +(import (rename (chibi json) (json->string base:json->string)) (srfi 1)) (begin (define json-object list) (define json-list vector) - (define json-null (if #f #f)) - (define json-object? list?) + (define json-null (string->json "null")) + + (define (json-object? obj) + (or (list? obj) + (json-record? obj))) + (define json-list? vector?) (define (json-object-contains-key? obj key) - (and (assoc key obj) #t)) + (or (and (list? obj) + (assoc key obj) + #t) + (and (json-record? obj) + (json-object-contains-key? (json-record->fields obj) key)))) (define (json-null? obj) (eq? obj json-null)) ;; json->string already defined in chibi json + (define (json->string json) + (if (json-record? json) + (json->string (json-record->fields json)) + (base:json->string json))) ;; string->json already defined in chibi json (define (json-object-ref json key) - (let ((pair (assoc key json))) - (if pair - (cdr pair) - ((json-key-not-found))))) + (cond + ((list? json) + (let ((pair (assoc key json))) + (if pair + (cdr pair) + ((json-key-not-found))))) + ((json-record? json) + (json-object-ref (json-record->fields json) key)) + (else (error "json-object-ref: not an object" json)))) (define json-list-ref vector-ref) (define json-list-length vector-length) - (define json-object->alist values) + + (define (json-object->alist json) + (cond + ((list? json) json) + ((json-record? json) (json-record->fields json)) + (else (error "json-object->alist: not an object" json)))) + (define json-list->list vector->list)) -- cgit