Skip to content

Instantly share code, notes, and snippets.

@jhunt
Created September 8, 2021 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhunt/20e11c88872525e6bb940bc5e2bb246a to your computer and use it in GitHub Desktop.
Save jhunt/20e11c88872525e6bb940bc5e2bb246a to your computer and use it in GitHub Desktop.
JSON encoding in Lisp!
(defun alist? (lst)
(cond ((null lst) t)
((listp lst) (and (consp (car lst))
(alist? (cdr lst))))
(t nil)))
(defun json-encode-obj (v)
(format nil "~{~a~^,~}"
(mapcar (lambda (pair)
(format nil "\"~(~a~)\":~a"
(car pair)
(json-encode (cdr pair))))
v)))
(defun json-encode-lst (v)
(format nil "~{~a~^,~}"
(mapcar #'json-encode v)))
(defun json-encode (v)
(cond ((eq t v) (format nil "true"))
((null v) (format nil "false"))
((alist? v) (format nil "{~a}" (json-encode-obj v)))
((listp v) (format nil "[~a]" (json-encode-lst v)))
((stringp v) (format nil "~s" v))
(t (format nil "~a" v))))
(let ((var `((a . 1)
(b . (1 "2" ,t , nil ((foo . "bar\"")) 3)))))
(format t "~a~%" (json-encode var)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment