json
json copied to clipboard
BUG:字符串的错误
当字符串里面本身带有引号时,json->string方法输出的格式有问题。需要对字符串进行转换处理。 使用你的core库解决此问题。
$ git diff -w HEAD
diff --git a/json.sc b/json.sc
index 29f92e1..6748fd3 100644
--- a/json.sc
+++ b/json.sc
@@ -36,6 +36,7 @@
(import
(scheme)
(only (core alist) vector->alist)
+ (only (core string) string-replace)
)
@@ -131,7 +132,7 @@
(define f
(lambda (x)
(cond
- ((string? x) (string-append "\"" x "\""))
+ ((string? x) (string-append "\"" (string-replace x "\"" "\\\"") "\""))
((number? x) (number->string x))
((symbol? x) (symbol->string x)))))
这只能解决带成对匹配的引号的,但如果出现不成对的引号的话,仍然有问题。
我不明白 请指出可能导致错误的测试用例
之前我专门测试过这个引号
-DGIT_COMMIT="字符串" 这里出错了。
-DSVN_COMMIT="字符串" 这里也是一样。
$ cat test.ss
(import (json json))
(define test-json
'(("arguments" . #(
"-DDATE_Ymd=0x20200530"
"-DVERSION_NO=0"
"-DGIT_COMMIT=\"c4b5d646f2b3d0ec0adc97ef98e1bfcaa6dcd0bf\""
"-DSVN_COMMIT=\"\""
"-Iapplication/"
"main.c"))
("directory" . "project/")
("file" . "main.c")))
(define test-string (json->string test-json))
(format #t "json: ~a\n" test-json)
(format #t "string: ~a\n" test-string)
$ scheme --script test.ss
json: ((arguments . #(-DDATE_Ymd=0x20200530 -DVERSION_NO=0 -DGIT_COMMIT="c4b5d646f2b3d0ec0adc97ef98e1bfcaa6dcd0bf" -DSVN_COMMIT="" -Iapplication/ main.c)) (directory . project/) (file . main.c))
string: {"arguments":["-DDATE_Ymd=0x20200530","-DVERSION_NO=0","-DGIT_COMMIT="c4b5d646f2b3d0ec0adc97ef98e1bfcaa6dcd0bf"","-DSVN_COMMIT=""","-Iapplication/","main.c"],"directory":"project/","file":"main.c"}
$
这次我在 "arguments:" 前面加了个引号(没有成对),在转为string的时候没有问题,但是在再次转为json信息的时候出问题了。
$ cat test.ss
(import (json json))
(define test-json
'(("\"arguments" . #(
"-DDATE_Ymd=0x20200530"
"-DVERSION_NO=0"
"-DGIT_COMMIT=\"c4b5d646f2b3d0ec0adc97ef98e1bfcaa6dcd0bf\""
"-Iapplication/"
"main.c"))
("directory" . "project/")
("file" . "main.c")))
(define test-string (json->string test-json))
(define test-json2 (string->json test-string))
(format #t "json: ~a\n" test-json)
(format #t "string: ~a\n" test-string)
(format #t "json2: ~a\n" test-json2)
$ scheme --script test.ss
Exception in read: unexpected end-of-file reading list at char 1 of #<input port string>
$
所以目前看上去,key和value,只要带有引号在转来转去的过程中就会出现问题。
待我试一试