Skip to content

Instantly share code, notes, and snippets.

@vaguecoder
Last active May 21, 2021 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaguecoder/37086acb50919a95ef025e0f05c27b61 to your computer and use it in GitHub Desktop.
Save vaguecoder/37086acb50919a95ef025e0f05c27b61 to your computer and use it in GitHub Desktop.
This takes JSON as object and returns slice of all the leaf key-value pairs in the structure. This doesn't preserve details of the depth, but just KVs of all levels. More details in: https://github.com/VagueCoder/Random-Go-Snippets/
package unmarshal
import (
"fmt"
"reflect"
)
// keyValuePairs takes in map[string]interface{} as interface{} and returns map[string]string
// In simpler words, it takes map of uncertain levels and returns the leaf key-value pairs.
func keyValuePairs(m interface{}) map[string]string {
// Using goroutines, channels or receiver here will definitely add value to execution.
// But the aim here is to keep the demonstration simple and closer to native code.
kvs := make(map[string]string)
if reflect.ValueOf(m).Kind() == reflect.Map {
// When interface type is a map.
// Eg.: map0, map1, map2, map3, map4, map5
mp, ok := m.(map[string]interface{})
if ok {
// When map type is map[string]interface{}.
// i.e., it may have more levels inside.
// Eg.: map0, map2, map4
for k, v := range mp {
if reflect.ValueOf(v).Kind() == reflect.String {
// When value type is string.
// i.e., only leaf item.
// Eg.: key1-8 (all)
kvs[k] = v.(string)
} else {
// When value type is map[string]interface{}.
// i.e., if may have more maps inside.
// Eg.: map0, map2, map4
// keyValuePairs calls itself recursively till leaf items
for nk, nv := range keyValuePairs(v) {
// Add key-values pairs of inner levels to outer
kvs[nk] = nv
}
}
}
} else {
// When map type is not map[string]interface{}, but just map[string]string.
// i.e., has leaf items but no sub-levels.
// Eg.: map1, map3, map5
for k, v := range m.(map[string]string) {
// Add key-values pairs of map to result
kvs[k] = v
}
}
}
return kvs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment