我正在尝试使用 YASON 对 alist 中的 JSON 字符串进行编码。问题是,我得到的返回值是我输入的原始列表。它正在打印 JSON 字符串,并根据 the documentation ,它会转到*STANDARD-OUTPUT*
。
简单的示例 session :
(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]
如何将 {"foo":"bar","baz":"qux"}
放入 starving-json-eater
中?
最佳答案
您可以使用WITH-OUTPUT-TO-STRING
临时将变量绑定(bind)到写入字符串的打开流。您甚至可以绑定(bind)特殊变量*standard-output*
,以便您只更改代码的动态上下文,而无需显式提供不同的流参数(例如当您使用进程重定向流时)。
(with-output-to-string (*standard-output*)
(yason:encode-alist '(("a" . "b"))))
请注意,绑定(bind) *standard-output*
意味着写入 *standard-output*
的任何内容最终都会在 范围内写入字符串中>with-output-to-string
。在上述情况下,范围受到足够的限制,以避免意外捕获嵌套代码的输出。您还可以使用词法变量来精确控制谁可以写入字符串:
(with-output-to-string (json)
(yason:encode-alist '(("a" . "b")) json))
关于json - 如何获取 yason :encode-alist to return the encoded string instead of sending it to a stream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52044947/