0
votes

I am new Clojurescript and want to hack arround with clojurescript and electron based on an small json file.

I am doing something like (with transit/cljs)

(def jsondata (t/read (t/reader :json) (.readFileSync fs path_to_file "utf8")))) )

first I check if status is ok, that works fine...

(let [json_status (get jsondata "status")]
      (.log js/console "JSON Glossar Status:" json_status))

now, how can I access one of the maps in the pages array, or step through the map?

{"status":"ok",
    "pages":[
        {
            "id":1,
            "name":"name1",
            "image":"imagename1.png",
            "children":[
                {
                    "id":1,
                    "copytext":"kdjsldjsljfl"
                },
                {
                    "id":2,
                    "copytext":"dksdöfksöfklsöf"
                }
            ]
        },
        {
            "id":2,
            "name":"name1",
            "image":"imagename1.png",
            "children":[
                {
                    "id":4,
                    "copytext":"kdjsldjsljfl"
                },
                {
                    "id":5,
                    "copytext":"dksdöfksöfklsöf"
                }
            ]
        }
    ]
   }
2

2 Answers

1
votes

You can use aget (i.e. "array get") for nested ClojureScript / JavaScript interop.

For example, if you wanted to access the second map item in your "pages" array, you could do this:

(def my-js-object
  (clj->js {:status "ok"
            :pages [{:id 1
                     :name "foo"
                     :children []}
                    {:id 2
                     :name "bar"
                     :children []}]}))

(aget my-js-object "pages" 1)

In the above code I'm simply using clj->js to construct a notional (and incomplete) representation of your JSON; I hope this is enough to make sense.

My REPL output was:

#js {:id 2, :name "bar", :children #js []}

If you wanted to do something more complex with each page item, e.g. "map over each page hashmap and pull out the name values", then you could make use of the .- JS property accessor

(->> (.-pages my-js-object)
     (map #(.-name %)))

REPL output:

 ("foo" "bar")
0
votes

To not answer the question, you could use js->cljs, https://cljs.github.io/api/cljs.core/js-GTclj, to turn your json into a normal Clojure data structure and use Clojures normal fns to extract the data you want.