Created
October 20, 2021 21:24
-
-
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.
This file contains hidden or 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
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