json.scm 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2018, 2019 Ludovic Courtès <ludo@gnu.org>
  3. ;;;
  4. ;;; This file is part of GNU Guix.
  5. ;;;
  6. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  7. ;;; under the terms of the GNU General Public License as published by
  8. ;;; the Free Software Foundation; either version 3 of the License, or (at
  9. ;;; your option) any later version.
  10. ;;;
  11. ;;; GNU Guix is distributed in the hope that it will be useful, but
  12. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;;; GNU General Public License for more details.
  15. ;;;
  16. ;;; You should have received a copy of the GNU General Public License
  17. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  18. (define-module (guix json)
  19. #:use-module (json)
  20. #:use-module (srfi srfi-9)
  21. #:export (define-json-mapping))
  22. ;;; Commentary:
  23. ;;;
  24. ;;; Helpers to map JSON objects to SRFI-9 records. Taken from (guix swh).
  25. ;;;
  26. ;;; Code:
  27. (define-syntax-rule (define-json-reader json->record ctor spec ...)
  28. "Define JSON->RECORD as a procedure that converts a JSON representation,
  29. read from a port, string, or hash table, into a record created by CTOR and
  30. following SPEC, a series of field specifications."
  31. (define (json->record input)
  32. (let ((table (cond ((port? input)
  33. (json->scm input))
  34. ((string? input)
  35. (json-string->scm input))
  36. ((or (null? input) (pair? input))
  37. input))))
  38. (let-syntax ((extract-field (syntax-rules ()
  39. ((_ table (field key json->value))
  40. (json->value (assoc-ref table key)))
  41. ((_ table (field key))
  42. (assoc-ref table key))
  43. ((_ table (field))
  44. (assoc-ref table
  45. (symbol->string 'field))))))
  46. (ctor (extract-field table spec) ...)))))
  47. (define-syntax-rule (define-json-mapping rtd ctor pred json->record
  48. (field getter spec ...) ...)
  49. "Define RTD as a record type with the given FIELDs and GETTERs, à la SRFI-9,
  50. and define JSON->RECORD as a conversion from JSON to a record of this type."
  51. (begin
  52. (define-record-type rtd
  53. (ctor field ...)
  54. pred
  55. (field getter) ...)
  56. (define-json-reader json->record ctor
  57. (field spec ...) ...)))