function | since v0.0-927 | Edit |
(js->clj x)
(js->clj x & opts)
Recursively transforms JavaScript arrays into ClojureScript vectors, and JavaScript objects into ClojureScript maps.
With option {:keywordize-keys true}
will convert object fields from strings to
keywords.
Note that js->clj
is not optimized for speed and the transit.cljs library is
recommended for parsing large amounts of JSON data.
Parse a JSON string:
(def json "{\"foo\": 1, \"bar\": 2, \"baz\": [1,2,3]}")
(def a (.parse js/JSON json))
;;=> #js {:foo 1, :bar 2, :baz #js [1 2 3]}
Convert JSON data a
to ClojureScript data:
(js->clj a)
;;=> {"foo" 1, "bar" 2, "baz" [1 2 3]}
(js->clj a :keywordize-keys true)
;;=> {:foo 1, :bar 2, :baz [1 2 3]}
Recursively transforms JavaScript arrays into ClojureScript vectors, and JavaScript objects into ClojureScript maps. With option ':keywordize-keys true' will convert object fields from strings to keywords.
(defn js->clj
([x] (js->clj x :keywordize-keys false))
([x & opts]
(let [{:keys [keywordize-keys]} opts
keyfn (if keywordize-keys keyword str)
f (fn thisfn [x]
(cond
(satisfies? IEncodeClojure x)
(-js->clj x (apply array-map opts))
(seq? x)
(doall (map thisfn x))
(map-entry? x)
(MapEntry. (thisfn (key x)) (thisfn (val x)) nil)
(coll? x)
(into (empty x) (map thisfn) x)
(array? x)
(persistent!
(reduce #(conj! %1 (thisfn %2))
(transient []) x))
(identical? (type x) js/Object)
(persistent!
(reduce (fn [r k] (assoc! r (keyfn k) (thisfn (gobject/get x k))))
(transient {}) (js-keys x)))
:else x))]
(f x))))