Commit a1fabc65 authored by Ludovic Courtès's avatar Ludovic Courtès
Browse files

json: Add support for record-to-json conversion.

* jupyter/json.scm (define-json-writer): New macro.
(define-json-mapping): Add support for defining writers.
parent 42aea28f
...@@ -46,15 +46,44 @@ following SPEC, a series of field specifications." ...@@ -46,15 +46,44 @@ following SPEC, a series of field specifications."
(symbol->string 'field)))))) (symbol->string 'field))))))
(ctor (extract-field table spec) ...))))) (ctor (extract-field table spec) ...)))))
(define-syntax-rule (define-json-mapping rtd ctor pred json->record (define-syntax-rule (define-json-writer record->json
(field getter spec ...) ...) (field-spec ...) ...)
"Define RTD as a record type with the given FIELDs and GETTERs, à la SRFI-9, "Define RECORD->JSON as a procedure that returns an alist, the Guile-JSON
and define JSON->RECORD as a conversion from JSON to a record of this type." representation of the given record."
(begin (define (record->json record)
(define-record-type rtd (let-syntax ((field->alist (syntax-rules ()
(ctor field ...) ((_ field getter)
pred (cons (symbol->string 'field)
(field getter) ...) (getter record)))
((_ field getter key _ value->json)
(cons key
(value->json (getter record))))
((_ field getter key _ (... ...))
(cons key
(getter record))))))
(list (field->alist field-spec ...) ...))))
(define-json-reader json->record ctor (define-syntax define-json-mapping
(field spec ...) ...))) (syntax-rules (<=>)
"Define RTD as a record type with the given FIELDs and GETTERs, à la SRFI-9,
and define JSON->RECORD as a conversion from JSON to a record of this type.
Optionally, define RECORD->JSON as the conversion from a record of this type
to its JSON representation (an alist)."
((_ rtd ctor pred json->record <=> record->json
(field getter spec ...) ...)
(begin
(define-json-mapping rtd ctor pred json->record
(field getter spec ...) ...)
(define-json-writer record->json
(field getter spec ...) ...)))
((_ rtd ctor pred json->record
(field getter spec ...) ...)
(begin
(define-record-type rtd
(ctor field ...)
pred
(field getter) ...)
(define-json-reader json->record ctor
(field spec ...) ...)))))
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment