gpt4 book ai didi

json - 在 lisp 中输入/输出 json 文件

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:54 26 4
gpt4 key购买 nike

大家早上好

为了完成这个项目,我再次需要你的帮助。

所以现在我正在尝试创建两个函数来在 lisp 中读取/写入文件。

这是函数必须如何工作的描述

    (json-load filename) -> JSON

(json-write JSON filename) -> filename

The json-load function opens the file filename returns a JSON object (or generates an error). If
filename does not exist the function generates an error. The suggestion is to read the whole file in one
string and then to call json-parse.
The json-write function writes the JSON object to the filename file in JSON syntax. If
filename does not exist, it is created and if it exists it is overwritten. Of course it is expected that
CL-PROMPT> (json-load (json-write '(json-obj # | stuff | #) "foo.json"))
(json-obj # | stuff | #)

这是我的 json 加载函数

(defun json-load (filename)
(with-open-file (file-stream filename)
(let ((file-contents (make-string (file-length file-stream))))
(read-sequence file-contents file-stream)
file-contents)) (json-parse (file-contents)))

但它不起作用

我也需要一些帮助来编写函数。

谢谢大家

编辑 1:

(defun json-load (filename)
(with-open-file (in filename
:direction :input
:if-does-not-exist :error)
(file-get-contents filename))
(json-parse filename))

(defun file-get-contents (filename)
(with-open-file (stream filename)
(let ((contents (make-string (file-length stream))))
(read-sequence contents stream)
contents)))

所以该函数应该不远就是正确的,但我认为问题在于文件获取内容函数。我认为,因为如果我运行这个函数,输出是

"\"{\\\"nome\\\":\\\"Arthur\\\",\\\"cognome\\\":\\\"Dent\\\"}\""

因此 json-parse 不再识别 json-object。有什么想法吗?

编辑 2:

我尝试了这两个功能,但结果相同。如果我在文件中使用相同的 json-object 调用 json-parse,那没问题,但如果我调用 json-load lisp,则用我自己的错误消息“undefined JSON object (json-parse)”响应我。为什么?

编辑 3:

这是 json-write 函数,但目前还不起作用。

    (defun json-write (json filename)
(with-open-file (out filename
:direction :output
:if-exists :overwrite
:if-does-not-exist :create)
(pprint (json out))))

所以帖子开头的描述说json-write函数以JSON语法将JSON对象写入文件名文件。现在,2 个问题

1) 我的功能是部分正确的吗?

2) 如何用 Json 语法编写 Json 对象?

谢谢

最佳答案

我正在做同一个项目,希望教授们不介意我们分享信息;)这是我采用的方法:

(defun json-load (filename)
(with-open-file (in filename
:direction :input
:if-does-not-exist :error)
(multiple-value-bind (s) (make-string (file-length in))
(read-sequence s in)
(json-parse s))))

请记住,read-sequence 会覆盖给定的序列,在本例中为 s。我只是简单地使用 multiple-value-bind 这样我就不必使用变量声明或 lambda 函数(尽管它只是 (let (( v form)) ...)),正如@tfb 指出的那样)。

关于json - 在 lisp 中输入/输出 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com