问题
我面临着从json对象中删除不需要的数组的问题。仅包含一个不是对象或数组的元素的数组。 (没有数组作为输入的根)
例
在:
{"name": [{ "inner": ["test"] }]}
想要:
{"name": [{ "inner": "test" }]}
方法
我从对解析的
map[string]interface{}
的值进行简单的类型切换开始,认识到它将不会切换为[]map[string]interface{}
大小写。 (举个例子)所以这是我想出的实现。它适用于大多数情况,但不适用于数组中的内部对象。
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
}
题
如何将大小写切换到对象数组,以便也可以递归地解析该数组中的对象?
最佳答案
您可以使用此功能删除不需要的数组。
func removearr(x interface{}) interface{} {
switch val := x.(type) {
case map[string]interface{}:
for k, v := range val {
val[k] = removearr(v)
}
return val
case []interface{}:
if len(val) == 1 {
// remove array only if the value is not an object
if _, ok := val[0].(map[string]interface{}); !ok {
return removearr(val[0])
}
}
for i, v := range val {
val[i] = removearr(v)
}
return val
default:
return x
}
}
https://play.golang.com/p/mwo7Y2rJ_lc