【CLisp】JSON解析簡單實現

使用說明:

(defvar json-string "[a,b,c:{c:1,d:2},e]")
(print (json-cvt json-string))

解析結果:

實現:

;;;; json convert
;;;; WHJ.20180916

(defun define-macro-character-function (char-end)
    (lambda (stream char)
        (let ((cnt 0))
            (coerce
                (loop for x = (read-char stream char-end)
                    if (char= x char) 
                        collect x
                        and 
                        do (incf cnt)
                    else if (zerop cnt) 
                            if (char= x char-end)
                                do (loop-finish)
                            else
                                collect x
                         else
                            if (char= x char-end)
                                collect x
                                and
                                do (incf cnt -1)
                            else
                                collect x)
                'string))))
(defun macro-character-comma (stream char)
     'null)
(defun macro-character-colon (stream char)
     'null)
(defun json-cvt-1 (json-string)
    (let ((*readtable* (copy-readtable)))
        (set-macro-character #\{ (define-macro-character-function #\}))
        (set-macro-character #\[ (define-macro-character-function #\]))
        (set-macro-character #\, #'macro-character-comma)
        (set-macro-character #\: #'macro-character-colon)
        
        (with-input-from-string (in json-string)
                    (loop for x = (read in nil)
                        while x
                            if (not (eq x 'null))
                                collect x))))
(defun json-cvt (json-string)
    (let ((json-obj-list (json-cvt-1 json-string)))
         (loop for i from 0 below (length json-obj-list)
               for x = (nth i json-obj-list)
               if (stringp x)
                    do (setf (nth i json-obj-list) (json-cvt x)))
        (if (cdr json-obj-list)
            json-obj-list
            (car json-obj-list))))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章