Skip to content

Instantly share code, notes, and snippets.

@mikeball
Created February 10, 2016 09:52
Show Gist options
  • Save mikeball/04d35cc80d4faa7b84f7 to your computer and use it in GitHub Desktop.
Save mikeball/04d35cc80d4faa7b84f7 to your computer and use it in GitHub Desktop.
Flatten nested maps to csv
(def json-raw
[{"type" "t1"
"weather" { "lat" 1
"lon" 2}}
{"type" "t2"
"weather" { "lat" 3
"lon" 4
"abc" {"xyz" 5}}}])
(defn flatten-map [m parent-name]
(flatten
(for [[k v] m]
(let [pathname (str parent-name (if parent-name "/") k)]
(cond (map? v)
(flatten-map v pathname)
; handle vector values...
:default
[pathname v])
))))
(defn to-csv-map [m]
(apply hash-map (flatten-map m nil)))
(map to-csv-map json-raw)
;; => ({"weather/lat" 1, "weather/lon" 2, "type" "t1"} {"weather/abc/xyz" 5, "weather/lat" 3, "weather/lon" 4, "type" "t2"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment