我开始为大学的家庭作业编写下面的代码,其中包括在 Common Lisp 中解析 json 字符串。我现在面临的主要问题是获得正确的 substring\subsequence 以继续递归调用并解析字符串的其余部分。基本上主要思想是递归地检查整个字符串。按照给定的语法,输入字符串应该是:
1) "{\"nome\" : \"arturo\" , \"cognome\" : \"durone\" , \"età\" : \"22\" , \"corso\" : \"informatica\"}"
2) "{\"name\" : \"Zaphod\",\"heads\" : [[\"Head1\"], [\"Head2\"]]}"
3) "{\"name\" : \"Zaphod\",{property:value, property : [1,2,3] }
4) "[1,2,3]"
基本上我确实从字符串中删除了任何空格和任何 \" 得到一个干净的字符串 "{name:Zaphod,heads:[[Head1],[Head2]]}"
,在这里我检查位置':'
并获取从 0 到 的子序列((position ":")-1)
,第二部分也是如此,但是当我必须传递到时问题就来了递归调用,因为我不知道如何传递字符串的正确索引。
我试图检查函数在输出中提供给我的新列表的任何元素的长度,但它不起作用/帮助,因为字符串被拆分并且\"
初始输入中没有空格和字符。你能帮我找出一种方法来按照递归方法解析json字符串的其余部分吗?
> main function
(defun j-obj (str)
(cond ((correct_form str)
`(json-obj-aux(revome_braces (remove_backslash(remove_space str)))))))`
> aux function that thru a recursive call analize the whole string
(defun json-obj-aux (str)
(cond ((= (length str) 0)nil)
((cons (aux_control str)nil))))
; (json-obj-aux (subseq (shorter str)(length (aux_control (shorter str)))
; (length (shorter str))))))))
> check the whole string , splitting once it finds ":"
(defun aux_control (str)
(cons (subseq str 0 (search ":" str))(check_type (subseq str (+ (search ":" str) 1) (length str)))))
(defun check_type (str)
(cond ((equal (subseq str 0 1) "{")(obj_c str))
((equal (subseq str 0 1) "[")(cons (obj_array (remove_braces str))nil))
(t (cons (subseq str 0 (search "," str))nil))))
(defun obj_c (str)
"{")
(defun obj_array (str)
(cond ((= 0 (length str))nil)
((null (search "," str))(cons (subseq str (+ (search "[" str)1)(- (length str)1))nil))
((and (null (search "[" str))(null (search "," str)))(cons str nil))
((null (search "[" str))(cons (subseq str 0 (search "," str))
(obj_array (subseq str (+ (search "," str) 1)))))
((cons (subseq str (+ (search "[" str) 1)(search "]" str))
(obj_array (subseq str (+ (search "," str) 1)))))))
(defun remove_space (str)
(cond ((= 0 (length str))nil)
((concatenate 'string (remove_aux str) (remove_space(subseq str 1))))))
(defun remove_aux (str)
(cond ((equal (subseq str 0 1) " ")"")
((concatenate 'string (subseq str 0 1) ""))))
(defun remove_backslash (str)
(cond ((= 0 (length str))nil)
((concatenate 'string (remove_slash str)(remove_backslash(subseq str 1))))))
(defun remove_slash (str)
(cond ((equal (subseq str 0 1) "\"")"")
((concatenate 'string (subseq str 0 1) ""))))
(defun remove_braces (str)
(subseq str 1 (- (length str) 1)))
(defun shorter (str)
(subseq str 1 (length str)))
这就是我到目前为止所得到的,这并不是完全错误的,因为我可以解析部分 json-string。我无法真正解析的是整个原因我不知道如何传递新子序列的正确索引:
CL-USER 1 > (j-obj "{\"name\" : \"Zaphod\",\"heads\" : [[\"Head1\"], [\"Head2\"]]}")
(("name" "Zaphod"))
CL-USER 2 > (j-obj "{\"heads\" : [[\"Head1\"], [\"Head2\"]]}")
(("heads" ("Head1" "Head2")))
正确的输出应该是:
(("name" "Zaphod")("heads" ("Head1" "Head2")))