-
Notifications
You must be signed in to change notification settings - Fork 20
Getting Started
In order to read Transit encoded JSON you need to construct a reader:
(ns try-transit
(:require [cognitect.transit :as t]))
(def r (t/reader :json))
Currently :json
is the only type of reader available. Given a
a reader you can invoke cognitect.transit/read
.
For example reading a vector:
(def v (t/read r "[1,2,3]")) ;; [1 2 3]
And reading a map:
(def m (t/read r "{\"~:foo\":\"bar\"}")) ;; {:foo "bar"}
Like reading, writing is fairly straightforward. Constructing a writer looks very much like constructing a reader:
(ns try-transit
(:require [cognitect.transit :as t]))
(def w (t/writer :json))
Once you've constructed a writer you can invoke
cognitect.transit/write
to encode values.
For example writing a vector:
(t/write w [1 2 3]) ;; "[1,2,3]"
And writing a map:
(t/write w {:foo "bar"}) ;; "[\"^ \",\"~:foo\",\"bar\"]"
Maps get written out as JSON arrays as this form is more efficient for decoding. For debugging purposes it's useful to construct a verbose writer:
(def wv (t/writer :json-verbose))
And now the result of writing map-like values is easier to read:
(t/write wv {:foo "bar"}) ;; "{\"~:foo\":\"bar\"}"
This will return the string "{\"~:foo\":\"bar\"}"
.
Being able to easily write out graphs of ClojureScript values is one the big benefits of transit-cljs. transit-cljs will recursively encode graphs of values and Transit ground values like integers and dates need no special treatment.
To demonstrate this lets define some simple geometry primitives:
(deftype Rect [orgiin size])
(deftype Point [x y])
(deftype Size [width height])
(def arect (Rect. (Point. 0 0) (Size. 150 150)))