如何在文件中编写一些传输-clj,以及如何从该文件检索数据结构



我有:

(def c [{:id 12 :name "John"}])

我如何在一个文件中写这个?

我如何得到这个数据结构?

一个不完美的解决方案:

(require '[clojure.java.io :as io]
         '[cognitect.transit :as t])
(def c [{:id 12 :name "John"}])
(def dir "resources/json/")
(defn write-transit [dir file-name file-type coll]
  (let [suffix {:json ".json" :json-verbose ".verbose.json" :msgpack ".mp"}]
    (with-open [out (io/output-stream 
                      (str dir "/" file-name (file-type suffix)))]
        (t/write (t/writer out file-type) coll)))))
(defn read-transit [dir file-name file-type]
  (let [suffix {:json ".json" :json-verbose ".verbose.json" :msgpack ".mp"}]
    (with-open [in (io/input-stream (str dir "/" file-name (file-type suffix)))]
      (t/read (t/reader in file-type)))))
(write-transit dir "test" :json c)
;=> nil
(read-transit dir "test" :json)
;=> [{:id 12 :name "John"}]

看一下文档中的代码,尤其是底部的代码。

最新更新