json - 如何获取 yason :encode-alist to return the encoded string instead of sending it to a stream?

标签 json encoding stream common-lisp

我正在尝试使用 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/

相关文章:

Android - 更新多人游戏中所有客户端的用户界面?

ASP.NET MVC 将 JSON 从 Controller 传递给 View

javascript - Laravel 将 json 传递给 vue.js

java - U+FFFD 在此字体的编码中不可用 : WinAnsiEncoding

C# 字符串不支持西里尔字符

jquery - 使用MVC3的HTML编码和解码

c# - 将 FileStream 中的数据读入通用 Stream

ruby - 限制 ruby​​ 文件流的速率

javascript - Google Charts API - 如何向它传递 JSON 数据?

node.js - 传送响应时无法嵌入 EJS