Map to json

I’ve sent you a solution via PM, but for posterity:

(defn maps->csv [coll-of-maps]
  (let [header (-> coll-of-maps first keys)                               ;; we take the keys to use as a csv header 
        to-vals (apply juxt header)                                       ;; a function that will extract the map values in the same order as header
        lines (map (fn[m] (->> m                                          ;; we take m
                              to-vals                                     ;; extract the values
                              (clojure.string/join ", "))) coll-of-maps)  ;; and join them as strings
        header-string (->> header (map name) (clojure.string/join ", "))] ;; header string
    (str header-string "\n" (clojure.string/join "\n" lines))))           ;; the whole thing we want

(maps->csv [{:name "Edward" :glitter-index 10} {:name "Bella" :glitter-index 0}])
;; => "name, glitter-index\nEdward, 10\nBella, 0"

You should probably have a look at juxt over at clojuredocs.org. It’s a very useful function. In general, you can iterate over the values of a map using vals, but since maps are not ordered, and here you need the fields to be in the same order, we can use juxt to generate a function that gives us the values of the map in a vector, in consistent order.

A useful thing to do is to run this stuff in the CIDER debugger (or if you’re not using Emacs, execute each step with some example data) to see what is going on in each transformation. It’s all simple stuff, but it can be a bit confusing when you’re starting out.

For reference, the problem is at the end of this page: https://www.braveclojure.com/core-functions-in-depth/