Skip to content

Instantly share code, notes, and snippets.

@alaydeliwala
Created October 20, 2021 21:24
Show Gist options
  • Save alaydeliwala/6261a5b21613697df44e9a67fc89df7b to your computer and use it in GitHub Desktop.
Save alaydeliwala/6261a5b21613697df44e9a67fc89df7b to your computer and use it in GitHub Desktop.
Given an object (json), write code to extract all the keys from it.
func flattenJSON(source string) []string{
return flattenJSONWorker(source, "")
}
// source is the json object and parent initially is ""
func flattenJSONWorker(source string,parent string) []string{
res := make([]string,0)
var arr map[string]gjson.Result
if gjson.Parse(source).IsObject(){
arr = gjson.Parse(source).Map()
} else if gjson.Parse(source).IsArray(){
for index, item := range gjson.Parse(source).Array() {
log.Printf("%v, %v", index, item)
var temp []string
if parent == ""{
temp= flattenJSONWorker(item.Raw,strconv.Itoa(index))
}else{
temp = flattenJSONWorker(item.Raw,parent + ".[" + strconv.Itoa(index) + "]")
}
res = append(res,temp...)
}
} else{
return []string{parent}
}
for key,val := range arr{
var temp []string
if parent == ""{
temp= flattenJSONWorker(val.Raw,key)
}else{
temp = flattenJSONWorker(val.Raw,parent + "." + key)
}
res = append(res,temp...)
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment