summaryrefslogtreecommitdiff
path: root/lib/zambyte/meta/json.sld
diff options
context:
space:
mode:
Diffstat (limited to 'lib/zambyte/meta/json.sld')
-rw-r--r--lib/zambyte/meta/json.sld51
1 files changed, 51 insertions, 0 deletions
diff --git a/lib/zambyte/meta/json.sld b/lib/zambyte/meta/json.sld
index 3e27bd9..5542884 100644
--- a/lib/zambyte/meta/json.sld
+++ b/lib/zambyte/meta/json.sld
@@ -1,6 +1,7 @@
(define-library (zambyte meta json)
;; portable
(export json
+ define-json-record-type
json-ref
json-value?
@@ -41,6 +42,56 @@
value
(error "json: not a json value" value)))))
+ ;; TODO: implement this
+ (define (json-object-set! . args) #f)
+
+ (define-syntax handle-field-declarations
+ (syntax-rules ()
+ ((_ (field accessor))
+ (define (accessor obj)
+ (json-object-ref obj 'field)))
+ ((_ (field accessor mutator))
+ (begin
+ (define (accessor obj)
+ (json-object-ref obj 'field))
+ (define (mutator obj value)
+ (json-object-set! obj 'field value))))))
+
+ (define-syntax define-json-record-type
+ (syntax-rules ()
+ ((_ type
+ (constructor fields ...)
+ from-json-string
+ predicate
+ field-declarations ...)
+ (begin
+ (define (constructor fields ...)
+ (make-json-record 'type
+ (json-object `(fields . ,fields) ...)
+ from-json-string))
+
+ (define (predicate obj)
+ (cond
+ ((json-record? obj) (eq? (json-record->name obj) 'type))
+ ((json-object? obj) (and (json-object-contains-key? obj 'fields) ...))
+ (else #f)))
+
+ (define (from-json-string str)
+ (let ((json (string->json str)))
+ (parameterize ((json-key-not-found
+ (lambda ()
+ (error "key not found in json string when converting to a record" 'from-json-string))))
+ (constructor (json-ref json 'fields) ...))))
+
+ (handle-field-declarations field-declarations) ...))))
+
+ (define-record-type <json-record>
+ (make-json-record name fields from-json-string)
+ json-record?
+ (name json-record->name)
+ (fields json-record->fields)
+ (from-json-string json-record->from-json-string))
+
(define (json-ref json key . keys)
(let ((ref (cond ((json-object? json) json-object-ref)
((json-list? json) json-list-ref)