Problem
I'm facing the issue to remove not required arrays from an json object eg. arrays with only one element which is not an object or array. (No arrays as root of the input)
Example
In:
{"name": [{ "inner": ["test"] }]}
Wanted Out:
{"name": [{ "inner": "test" }]}
Approach
I started with a simple type switch on the values of a parsed map[string]interface{}
and recognized that it wont switch to the case []map[string]interface{}
. (Given example)
So here is the implementation I came up with. It works for most of the scenarios but not for inner Objects within an array yet.
type jsonMap map[string]interface{}
type jsonMapList []map[string]interface{}
m := jsonMap{}
err := json.Unmarshal(s, &m)
if err != nil {
panic(err)
}
res := removeFromObject(m)
bytes, err := json.Marshal(res)
if err != nil {
panic(err)
}
result := string(bytes)
log.Infof("Parse Result: %s", result)
func removeFromObject(in jsonMap) jsonMap {
res := jsonMap{}
for k, v := range in {
switch value := v.(type) {
case jsonMap:
res[k] = removeFromObject(value)
case jsonMapList:
list := []jsonMap{}
for _, entry := range value {
list = append(list, removeFromObject(entry))
}
res[k] = list
case []interface{}:
if len(value) == 1 {
res[k] = value[0]
} else {
res[k] = value
}
default:
res[k] = value
}
}
return res
}
Question
How do I switch case to an object array, so that I can recursively resolve the objects within that array too?