【发布时间】:2018-10-07 16:02:56
【问题描述】:
我正在尝试找到一种方法,将一个 JSON 字符串用作某种“模板”以应用于另一个 JSON 字符串。例如,如果我的模板如下所示:
{
"id": "1",
"options": {
"leatherseats": "1",
"sunroof": "1"
}
}
然后我将其应用于以下 JSON 字符串:
{
"id": "831",
"serial": "19226715",
"options": {
"leatherseats": "black",
"sunroof": "full",
"fluxcapacitor": "yes"
}
}
我想要一个如下的 JSON 字符串:
{
"id": "831",
"options": {
"leatherseats": "black",
"sunroof": "full",
}
}
不幸的是,我既不能依赖模板也不能依赖输入为固定格式,所以我不能编组/解组到已定义的接口。
我已经编写了一个遍历模板的递归函数,以构造一个字符串切片,其中包含要包含的每个节点的名称。
func traverseJSON(key string, value interface{}) []string {
var retval []string
unboxed, ok := value.(map[string]interface{})
if ok {
for newkey, newvalue := range unboxed {
retval = append(retval, recurse(fmt.Sprintf("%s.%s", key, newkey), newvalue)...)
}
} else {
retval = append(retval, fmt.Sprintf("%s", key))
}
return retval
}
我这样称呼这个函数:
template := `my JSON template here`
var result map[string]interface{}
json.Unmarshal([]byte(template), &result)
var nodenames []string
nodenames = append(nodenames, traverseJSON("", result)...)
然后我打算编写第二个函数,该函数使用这部分节点名称从输入的 JSON 字符串构造一个 JSON 字符串,但动力不足,并开始认为我可能走错了路。
对此的任何帮助将不胜感激。
【问题讨论】: