我正在尝试使用YASON对来自列表的JSON字符串进行编码。问题是,我得到的返回值是我提供给它的原始值。它正在打印JSON字符串,根据the documentation,它将发送给*STANDARD-OUTPUT*
。
简单的会话示例:
(ql:quickload :yason)
To load "yason":
Load 1 ASDF system:
yason
; Loading "yason"
(:YASON)
* (defparameter starving-json-eater (yason:encode-alist '(("foo" . "bar") ("baz" . "qux"))))
{"foo":"bar","baz":"qux"}
STARVING-JSON-EATER
* starving-json-eater
(("foo" . "bar") ("baz" . "qux"))
我尝试将'starving-json-eater
传递给stream
参数,但得到一个错误:
* (setf starving-json-eater (yason:encode-alist '(("foo" . "bar") ("baz" . "qux")) 'starving-json-eater))
debugger invoked on a SIMPLE-ERROR in thread
#<THREAD "main thread" RUNNING {1001E06783}>:
There is no applicable method for the generic function
#<STANDARD-GENERIC-FUNCTION SB-GRAY:STREAM-WRITE-CHAR (1)>
when called with arguments
(STARVING-JSON-EATER #\{).
Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [RETRY] Retry calling the generic function.
1: [ABORT] Exit debugger, returning to top level.
((:METHOD NO-APPLICABLE-METHOD (T)) #<STANDARD-GENERIC-FUNCTION SB-GRAY:STREAM-WRITE-CHAR (1)> STARVING-JSON-EATER #\{) [fast-method]
如何在starving-json-eater
中使用{"foo":"bar","baz":"qux"}
发布于 2018-08-28 05:57:45
您可以使用WITH-OUTPUT-TO-STRING
将一个变量临时绑定到一个打开的流,该流写入一个字符串。您甚至可以绑定特殊变量*standard-output*
,以便只更改代码的动态上下文,而不显式提供不同的流参数(就像您使用进程重定向流时一样)。
(with-output-to-string (*standard-output*)
(yason:encode-alist '(("a" . "b"))))
请注意,绑定*standard-output*
意味着在with-output-to-string
范围内写入*standard-output*
的任何内容最终都将写入字符串中。在上面的例子中,作用域受到了足够的限制,可以避免意外地从嵌套代码中捕获输出。您还可以使用词法变量来精确控制谁可以写入字符串:
(with-output-to-string (json)
(yason:encode-alist '(("a" . "b")) json))
发布于 2018-08-28 02:21:24
诀窍是创建一个一次性字符串输出流来捕获该值,然后从后面获取它:
* (ql:quickload :yason)
To load "yason":
Load 1 ASDF system:
yason
; Loading "yason"
(:YASON)
* (defparameter sated-json-eater (make-string-output-stream))
SATED-JSON-EATER
* (yason:encode-alist '(("foo" . "bar") ("baz" . "qux")) sated-json-eater)
(("foo" . "bar") ("baz" . "qux"))
* (defparameter json-string (get-output-stream-string sated-json-eater))
JSON-STRING
* json-string
"{\"foo\":\"bar\",\"baz\":\"qux\"}"
这可以隐藏在一个函数中:
(defun json-string-encode-alist (alist-to-encode)
(let ((stream (make-string-output-stream)))
(yason:encode-alist alist-to-encode stream)
(get-output-stream-string stream)))
https://stackoverflow.com/questions/52044947
复制相似问题