问题
I have some clojurescript that I want to interop with some javascript libraries. In my clojurescript code I do some analysis and come up with a list of maps. something like
[{:prop1 "value1" :prop2 "value2"}, {:prop1 "something else" :prop2 "etc"}...]
I need to pass this to a javascript functions as
[{prop1: "value1", prop2: "value2}, {..} ...]
I'm not sure how to return a javascript object form my clojurescript function though. Is there a way to serialize nested maps and lists to javascript objects. Or a way to create a new javascript object and then set properties on it?
回答1:
Just for the sake of people looking for something similar.
The ClojureScript core now contains a clj->js
function.
回答2:
I found a function here
(defn clj->js
"Recursively transforms ClojureScript maps into Javascript objects,
other ClojureScript colls into JavaScript arrays, and ClojureScript
keywords into JavaScript strings.
Borrowed and updated from mmcgrana."
[x]
(cond
(string? x) x
(keyword? x) (name x)
(map? x) (.-strobj (reduce (fn [m [k v]]
(assoc m (clj->js k) (clj->js v))) {} x))
(coll? x) (apply array (map clj->js x))
:else x))
Does exactly what I needed. There is also the inverse function, namely js->clj
in ClojureScript core.
回答3:
This works for me:
(defn clj->json
[ds]
(.stringify js/JSON (clj->js ds)))
usage:
(let [json (clj->json data-structure)]
;; do something with json
)
来源:https://stackoverflow.com/questions/10157447/how-do-i-create-a-json-in-clojurescript