How do I create a json in clojurescript

后端 未结 3 1493
醉酒成梦
醉酒成梦 2021-02-05 06:32

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

相关标签:
3条回答
  • 2021-02-05 06:54

    Just for the sake of people looking for something similar.

    The ClojureScript core now contains a clj->js function.

    0 讨论(0)
  • 2021-02-05 07:00

    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
      )
    
    0 讨论(0)
  • 2021-02-05 07:06

    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.

    0 讨论(0)
提交回复
热议问题