diff options
Diffstat (limited to 'weeb')
| -rw-r--r-- | weeb/struct.scm | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/weeb/struct.scm b/weeb/struct.scm index c3632f4..545c109 100644 --- a/weeb/struct.scm +++ b/weeb/struct.scm @@ -19,12 +19,15 @@ (define-module (weeb struct) #:use-module (ice-9 match) #:use-module (ice-9 regex) + #:use-module (json) #:export (define-struct make-struct instance-of? with-accessors call-with-slots - ref)) + ref + struct->json-string + json-string->struct)) ;; Define a new record type with the given NAME and FIELDS. (define-syntax define-struct @@ -88,3 +91,21 @@ instantiate the record's fields." (fields (cdr symbols))) (let ((quoted-fields (map (lambda (f) `',f) fields))) `(ref ,base-obj ,@quoted-fields))))))) + +(define (struct->json-string x) + (let ((descriptor (record-type-descriptor x))) + (scm->json-string + (map (lambda (field-name) + (cons + (symbol->string field-name) + ((record-accessor descriptor field-name) x))) + (record-type-fields descriptor))))) + +(define (json-string->struct type-descriptor x) + (let ((json-object (json-string->scm x))) + (apply + make-struct + type-descriptor + (map (lambda (field-name) + (assoc-ref json-object (symbol->string field-name))) + (record-type-fields type-descriptor))))) |