2

Say I have:

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

How do I write this in a file?

How do I get back this data structure?

Cœur
  • 37,241
  • 25
  • 195
  • 267
leontalbot
  • 2,513
  • 1
  • 23
  • 32

2 Answers2

1

Take a look at the code in the doc to read, especially at the bottom. There's a complete example of what you're looking for.

customcommander
  • 17,580
  • 5
  • 58
  • 84
hardcoder
  • 86
  • 2
  • Thanks. I believe the answer should use `cognitect.transit/read` and `cognitect.transit/write` functions though. See https://github.com/cognitect/transit-clj – leontalbot Aug 13 '14 at 10:37
1

A not perfect solution that works:

(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"}]
Marc Bollinger
  • 3,109
  • 2
  • 27
  • 32
leontalbot
  • 2,513
  • 1
  • 23
  • 32
  • It is worth noting: Transit is intended primarily as a wire protocol for transferring data between applications. If storing Transit data durably, readers and writers are expected to use the same version of Transit and you are responsible for migrating/transforming/re-storing that data when and if the transit format changes. (source Transit website) – Jacob Nov 14 '21 at 12:08