Skip to content

Instantly share code, notes, and snippets.

@edw
Last active February 16, 2025 12:04
Show Gist options
  • Select an option

  • Save edw/5a2118bb5a3b6ebdac7a6e81e49adce3 to your computer and use it in GitHub Desktop.

Select an option

Save edw/5a2118bb5a3b6ebdac7a6e81e49adce3 to your computer and use it in GitHub Desktop.
JSON parsing in Chibi Scheme using combinators
(import (chibi parse))
;; JSON Parsing
;; Edwin Watkeys
;; Nov 25, 2018
;;
;; Example usage:
;;
;; (parse datum "{\"foo\": true, \"bar\" : [0,1,2,3.14, .12]}")
;; => (("foo" #t)
;; ("bar" #(0 1 2 3.14 0.12000000000000001)))
;;
;; BUGS:
;;
;; 1. No string escape chars in strings.
;;
;; 2. Numeric parsing is embarassing.
;;
;; 3. Hash tables are not constructed in order to aid development as
;; hash-tables generally are a pain to print.
;;
(import (chibi parse))
(define-grammar json
(space ((* ,(parse-char char-whitespace?))))
(number ((-> n (+ (or ,(parse-char char-numeric?)
#\.)))
(string->number (list->string n))))
(string ((: ,(parse-char #\")
(-> s (* ,(parse-not-char #\")))
,(parse-char #\"))
(list->string s)))
(atom ((-> n ,number) n)
((-> s ,string) s)
("true" #t)
("false" #f))
(datum ((or ,atom ,array ,hash)))
(array-el ((: "," ,space (-> el ,datum)) el))
(array ((: "[" ,space (-> el ,datum) ,space
(-> els (* ,array-el)) ,space "]")
(apply vector el els))
((: "[" ,space "]") (vector)))
(hash-el ((: "," ,space (-> k ,string) ,space
":" ,space (-> v ,datum)) (list k v)))
(hash ((: "{" ,space (-> k ,string) ,space
":" ,space (-> v ,datum) ,space
(-> els (* ,hash-el)) ,space "}")
(apply list (list k v) els))
((: "{" ,space "}") (list))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment