Created
February 10, 2016 09:52
-
-
Save mikeball/04d35cc80d4faa7b84f7 to your computer and use it in GitHub Desktop.
Flatten nested maps to csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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