Created
February 18, 2015 23:10
-
-
Save sbocq/6aaeadcaa32acd1bc2db to your computer and use it in GitHub Desktop.
Flatten keys
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
;; (flatten-keys {:name {:first "Rich" :last "Hickey"} :number [1 415 123 4567]}) | |
;; => {"$.number[0]" 1, "$.number[1]" 415, "$.number[2]" 123, "$.number[3]" 4567, "$.name.first" "Rich", "$.name.last" "Hickey"} | |
(defn flatten-keys [thing] | |
(letfn [(-map-key [prefix k] (str prefix "." (name k))) | |
(-seq-key [prefix i] (str prefix "[" i "]")) | |
(-flatten-entry [make-key prefix result entry] | |
(let [[k v] entry] | |
(-flatten-thing result (make-key prefix k) v))) | |
(-flatten-thing [result key thing] | |
(cond (map? thing) | |
(reduce (partial -flatten-entry -map-key key) | |
result | |
(seq thing)) | |
(sequential? thing) | |
(reduce (partial -flatten-entry -seq-key key) | |
result | |
(map-indexed vector thing)) | |
:else (assoc! result key thing)))] | |
(persistent! | |
(-flatten-thing (transient {}) (if (map? thing) "$" "") thing)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment