Skip to content

Instantly share code, notes, and snippets.

@sbocq
Created February 18, 2015 23:10
Show Gist options
  • Save sbocq/6aaeadcaa32acd1bc2db to your computer and use it in GitHub Desktop.
Save sbocq/6aaeadcaa32acd1bc2db to your computer and use it in GitHub Desktop.
Flatten keys
;; (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