Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

string->json和json->string不配套的workthrough #1

Open
xaengceilbiths opened this issue Nov 5, 2019 · 1 comment
Open

string->json和json->string不配套的workthrough #1

xaengceilbiths opened this issue Nov 5, 2019 · 1 comment

Comments

@xaengceilbiths
Copy link

xaengceilbiths commented Nov 5, 2019

这个库就是ovenpasta本人写的。
其中string->json和json->string并不配套,我勉强改动使得输出的json文件可以被其他软件读(其缩进有严重问题)。我的做法是用json1->json2转成json->string识别的格式,json->string对boolean做了识别。建议r7rs用(rebottled json),r6rs要想想办法。
(rebottled json)的r7rs版本是 https://github.com/chaw/r7rs-libs/blob/master/rebottled/json.sld
(rebottled json)本身是 http://wiki.call-cc.org/eggref/5/json

@xaengceilbiths
Copy link
Author

(define (json1->json2 json)
  (cond [(list? json)
         (cons '@ (map cons
                    (map car json)
                    (map json1->json2 (map cdr json))))]
        [(vector? json)
         (map json1->json2 (vector->list json))]
        [(boolean? json) json]
        [(null? json) json]
        [(number? json) json]
        [(string? json) json]
        [(bytevector? json) json]
        [(symbol? json) json]))
(define (json->string json)
  (define special '((#\backspace . #\b) (#\newline . #\n) (#\alarm . #\a) 
		    (#\return . #\r) (#\tab #\t) (#\\ . #\\) (#\" . #\")))
  (cond [(and (pair? json)  (eq? (car json) '@))
	 (string-append 
	  "{\n"
	  (string-intersperse
	   (map (lambda (pair)
		  (let ([k (car pair)]
			[v (cdr pair)])
		    (string-append "  " (json->string k)
				   " : " (json->string v))))
	     (cdr json))
	   ",\n")
	  "\n}\n")]
	[(list? json)
	 (string-append  "["
			 (string-intersperse (map json->string json) ",")
			 "]\n")]
	[(number? json)
	 (number->string json)]
	[(string? json)
	 (string-append "\""
			(list->string (fold-right
					  (lambda (x acc)
					    (let ([q (assq x special)])
					      (if q (cons #\\ (cons (cdr q) acc))
						(cons x acc))))
					'()
					(string->list json)))
			"\"" )]
	[(bytevector? json)
	 (utf8->string json)]
        [(eq? json #t) "true"]
        [(eq? json #f) "false"]
        [(null? json) "null"]
	[(symbol? json)
	 (json->string (symbol->string json))]
	[else
	 (json->string "")]))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant