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

问题描述 投票:0回答:3

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

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

谢谢

维恩

json clojure
3个回答
1
投票

使用 clojure/data.json 库:

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

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

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

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

  • 然后将
    read-str
    slurp
    一起使用。我用以下内容制作了示例文件
    filename.json
{"name":"John", "age":30, "car":null}

然后这样读:

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

0
投票

那么,从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 值。


0
投票

在 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)))
© www.soinside.com 2019 - 2024. All rights reserved.