js->clj

functionsince v0.0-927Edit
(js->clj x)
(js->clj x & opts)

Details:

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.


Examples:

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]}

See Also:


Source docstring:
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.
Source code @ clojurescript:src/main/cljs/cljs/core.cljs
(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))))