首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >lisp中的输入/输出json文件

lisp中的输入/输出json文件
EN

Stack Overflow用户
提问于 2018-01-13 18:57:53
回答 1查看 609关注 0票数 2

大家早上好,

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

因此,现在我尝试创建两个函数来读/写lisp中的文件。

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

代码语言:javascript
复制
    (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-load函数

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

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

所以这个函数应该不远才能正确,但我认为问题在于file-get-content函数。我想这是因为如果我运行这个函数,输出是

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

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

编辑2:

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

编辑3:

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

代码语言:javascript
复制
    (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对象写入文件名文件。现在,有两个问题

1)这是我的函数部分正确吗?

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

谢谢

EN

回答 1

Stack Overflow用户

发布于 2018-01-13 20:33:35

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

代码语言:javascript
复制
(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指出的那样)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48239184

复制
相关文章

相似问题

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