首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何让yason:encode- it返回编码后的字符串,而不是将其发送到流?

如何让yason:encode- it返回编码后的字符串,而不是将其发送到流?
EN

Stack Overflow用户
提问于 2018-08-28 02:21:24
回答 2查看 111关注 0票数 2

我正在尝试使用YASON对来自列表的JSON字符串进行编码。问题是,我得到的返回值是我提供给它的原始值。它正在打印JSON字符串,根据the documentation,它将发送给*STANDARD-OUTPUT*

简单的会话示例:

代码语言:javascript
复制
(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参数,但得到一个错误:

代码语言:javascript
复制
* (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"}

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-28 05:57:45

您可以使用WITH-OUTPUT-TO-STRING将一个变量临时绑定到一个打开的流,该流写入一个字符串。您甚至可以绑定特殊变量*standard-output*,以便只更改代码的动态上下文,而不显式提供不同的流参数(就像您使用进程重定向流时一样)。

代码语言:javascript
复制
(with-output-to-string (*standard-output*)
  (yason:encode-alist '(("a" . "b"))))

请注意,绑定*standard-output*意味着在with-output-to-string范围内写入*standard-output*的任何内容最终都将写入字符串中。在上面的例子中,作用域受到了足够的限制,可以避免意外地从嵌套代码中捕获输出。您还可以使用词法变量来精确控制谁可以写入字符串:

代码语言:javascript
复制
(with-output-to-string (json)
  (yason:encode-alist '(("a" . "b")) json))
票数 3
EN

Stack Overflow用户

发布于 2018-08-28 02:21:24

诀窍是创建一个一次性字符串输出流来捕获该值,然后从后面获取它:

代码语言:javascript
复制
* (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\"}"

这可以隐藏在一个函数中:

代码语言:javascript
复制
(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)))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52044947

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档