从本地文件读取JSON与Clojure?



我很清楚如何从http请求解析JSON。但是我有一个JSON文件,我想在我的代码中使用。

我试图在谷歌上找到一个解决方案,但我正在努力弄清楚如何从文件系统读取本地JSON文件

感谢Vinn

使用clojure/data。json库:

  • 将此依赖项添加到project.clj:

[org.clojure/data.json "2.4.0"]

  • 将此需求添加到命名空间定义中:

(:require [clojure.data.json :as json])

  • 然后用read-strslurp。我制作了一个示例文件filename.json,内容如下:
{"name":"John", "age":30, "car":null}

,像这样读:

(json/read-str (slurp "filename.json"))
=> {"name" "John", "age" 30, "car" nil}

那么,从http请求到达的json和从本地文件到达的json有什么区别呢?我想真正的问题是"如何从本地文件读取",不是吗?

下面是如何使用clojure/data.json从字符串中读取json:
(def json-str (json/read-str "{"a":1,"b":{"c":"d"}}"))
现在,让我们将相同的字符串放入文件
echo '{"a":1,"b":{"c":"d"}}' > /tmp/a.json

让我们从文件中读取:

(def from-file (slurp "/tmp/a.json"))
(def json-file (json/read-str from-file))

确保它们是相同的:

(when (= json-str json-file)
(println "same" json-file))

打印"same"和解析后的json值。

最新更新