awwx.ws

Creating a parser combinator library to parse JSON

Prev: Displaying the parse resultContentsNext: alt

Matching JSON literals

I’ll steal an image from json.org:

Matching a JSON “true” and returning t on a successful match is easy:

(def json-true (p)
  (if (begins p (coerce "true" 'cons))
       (return (nthcdr 4 p) t)))
arc> (show-parse json-true "true,1,2,3")
returning: t remaining: ,1,2,3
nil
arc> (show-parse json-true "1,2,3")
no match
nil

To match any literal string, I can factor out the string that’s being matched and the return value:

(def match-literal (pat val)
  (with (patlist (coerce pat 'cons)
         patlen  len.pat)
    (fn (p)
      (if (begins p patlist)
           (return (nthcdr patlen p) val)))))

and make parsers for the JSON literals:

(= json-true  (match-literal "true"  t))
(= json-false (match-literal "false" nil))
(= json-null  (match-literal "null"  nil))
arc> (show-parse json-false "false")
returning: nil remaining: 
nil

Prev: Displaying the parse resultContentsNext: alt


Questions? Comments? Email me andrew.wilcox [at] gmail.com