You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Clojure读取本地文件系统中的JSON文件?

Clojure 读取本地JSON文件实现方法

你已经掌握HTTP请求中JSON的解析逻辑的话,整个流程只需要补「从本地文件系统获取输入流」这一步,后续解析逻辑和处理HTTP请求JSON完全一致,不需要特殊的文件专用JSON解析API。


通用推荐方案:使用Cheshire库

Cheshire是Clojure生态最常用的JSON解析库,性能好、API和处理HTTP请求时的使用习惯完全对齐,绝大多数生产项目都用这个方案。

  • 先添加依赖:
    • Leiningen项目在project.clj的:dependencies中添加:[cheshire "5.12.0"]
    • deps.edn项目添加依赖:cheshire/cheshire {:mvn/version "5.12.0"}
  • 实现代码:
;; 引入必要命名空间
(require '[cheshire.core :as json]
         '[clojure.java.io :as io])

(defn read-local-json
  "读取指定路径的本地JSON文件,自动将JSON键转为keyword"
  [file-path]
  (with-open [file-reader (io/reader file-path :encoding "UTF-8")]
    (json/parse-stream file-reader true)))

;; 调用示例
;; 读相对路径文件
(def app-config (read-local-json "./config/app.json"))
;; 读绝对路径文件
(def test-data (read-local-json "/data/test/dataset.json"))

如果JSON文件存放在项目resources目录下,打包成Jar后也需要正常读取的话,用io/resource获取classpath下的文件流即可:

(defn read-classpath-json [resource-path]
  (with-open [file-reader (io/reader (io/resource resource-path) :encoding "UTF-8")]
    (json/parse-stream file-reader true)))

;; 调用示例:读resources目录下的rules.json
(def rule-config (read-classpath-json "rules.json"))

无第三方依赖方案:使用Clojure官方JSON库

如果不想引入额外第三方依赖,可以用Clojure官方维护的data.json库:

  • 依赖说明:Clojure 1.11+版本已内置该库,低版本需要手动添加依赖[org.clojure/data.json "2.4.0"]
  • 实现代码:
(require '[clojure.data.json :as json]
         '[clojure.java.io :as io])

(defn read-local-json-builtin [file-path]
  (with-open [file-reader (io/reader file-path :encoding "UTF-8")]
    (json/read file-reader :key-fn keyword)))

注意事项

  • 不要直接用(json/parse-string (slurp file-path))的方式读大文件,slurp会把整个文件全量加载到内存,解析10M以上的JSON很容易触发内存溢出,上面示例里传入reader走流式解析的方式内存占用更稳定。
  • 务必用with-open包裹文件流操作,方法执行完会自动关闭文件句柄,避免出现文件句柄泄漏的问题。
  • 如果遇到中文乱码,显式给io/reader指定:encoding "UTF-8"即可解决,部分Windows环境下默认编码不是UTF-8容易出这个问题。

内容的提问来源于stack exchange,提问作者Vinn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 11:09:28