Skip to content

Instantly share code, notes, and snippets.

Created September 8, 2021 13:49
What would you like to do?
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))))
(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