我非常清楚如何从 http 请求中解析 JSON。但我本地有一个 JSON 文件,我想在我的代码中使用。
我试图在谷歌上找到解决方案,但我很难弄清楚如何从文件系统读取本地 JSON 文件
谢谢
维恩
使用 clojure/data.json 库:
project.clj
:[org.clojure/data.json "2.4.0"]
(:require [clojure.data.json :as 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 值。
在 clojure 中你可以使用 dep:
cheshire {:mvn/version "5.10.1"}
导入类:
:require
[cheshire.core :as json]
并使用此函数并返回给您一个映射
(defn read-invoice [file-path]
(with-open [rdr (io/reader file-path)]
(json/parse-stream rdr true)))