使用 Clojure 从本地文件读取 JSON?

Reading JSON from local file with Clojure?

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

我试图在 google 上找到解决方案,但我正在努力弄清楚如何从文件系统

读取本地 JSON 文件

谢谢

维恩

使用clojure/data.json库:

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

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

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

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

  • 然后使用read-str with slurp。我用以下内容制作了示例文件 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))

这将打印“相同”和解析的 json 值。