summaryrefslogtreecommitdiff
path: root/lib/zambyte/meta/chibi.scm
diff options
context:
space:
mode:
authorRobby Zambito <contact@robbyzambito.me>2023-02-17 00:27:42 -0500
committerRobby Zambito <contact@robbyzambito.me>2023-02-17 00:27:42 -0500
commit3600a2c69e6f03e2db23900f7bc7caf088460836 (patch)
tree56afbee6e9e7fdbdd23c65631fbaa8e9bc97f49d /lib/zambyte/meta/chibi.scm
parent61660091e2d05281791b24e775c5fdde93fd93df (diff)
Finish basic json-record functionality.
Can serialize and deserialize nested records correctly. Add json-object-map and json-list-map to facilitate recursively demoting records. Add json-object-set! to make the record mutators functional.
Diffstat (limited to 'lib/zambyte/meta/chibi.scm')
-rw-r--r--lib/zambyte/meta/chibi.scm37
1 files changed, 31 insertions, 6 deletions
diff --git a/lib/zambyte/meta/chibi.scm b/lib/zambyte/meta/chibi.scm
index 7cc777d..ba5a919 100644
--- a/lib/zambyte/meta/chibi.scm
+++ b/lib/zambyte/meta/chibi.scm
@@ -1,5 +1,7 @@
(import (rename (chibi json) (json->string base:json->string))
- (srfi 1))
+ (scheme case-lambda)
+ (srfi 1)
+ (srfi 2))
(begin
(define json-object list)
(define json-list vector)
@@ -21,11 +23,9 @@
(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)))
+ (base:json->string (json->typeless-json json)))
+
;; string->json already defined in chibi json
(define (json-object-ref json key)
@@ -37,11 +37,36 @@
((json-key-not-found)))))
((json-record? json)
(json-object-ref (json-record->fields json) key))
- (else (error "json-object-ref: not an object" json))))
+ (else ((json-key-not-found)))))
+
+ (define (json-object-set! json key value)
+ (cond
+ ((and (list? json)
+ (json-object-contains-key? json key))
+ (set-cdr! (assoc key json) value))
+ ((null? json)
+ (error "json-object-set!: cannot set on an empty object" json))
+ ((list? json)
+ (append! json (list (cons key value))))
+ ((json-record? json)
+ (or (and-let* ((pair (assoc key (json-record->mutators json)))
+ (mutator (cdr pair)))
+ (mutator json value))
+ (error "json-object-set!: no mutator for field" (json-record->name json) key)))))
(define json-list-ref vector-ref)
(define json-list-length vector-length)
+ (define (json-object-map proc json)
+ (map (lambda (pair)
+ (call-with-values (lambda () (proc (car pair) (cdr pair)))
+ (case-lambda
+ ((key value) (cons key value))
+ (_ (error "json-object-map: wrong return wrong number of values")))))
+ json))
+
+ (define json-list-map vector-map)
+
(define (json-object->alist json)
(cond
((list? json) json)