JSON encoding in Lisp!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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