相关疑难解决方法(0)

JSON字符串的交集

我正在尝试找到一种方法来使用一个JSON字符串作为各种"模板"来应用于另一个JSON字符串.例如,如果我的模板如下所示:

{
   "id": "1",
   "options": {
      "leatherseats": "1",
      "sunroof": "1"
   }
}
Run Code Online (Sandbox Code Playgroud)

然后我将其应用于以下JSON字符串:

{
   "id": "831",
   "serial": "19226715",
   "options": {
      "leatherseats": "black",
      "sunroof": "full",
      "fluxcapacitor": "yes"
   }
}
Run Code Online (Sandbox Code Playgroud)

我想要一个结果JSON字符串如下:

{
   "id": "831",
   "options": {
      "leatherseats": "black",
      "sunroof": "full",
   }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我不能依赖模板和输入是固定格式的,所以我不能编组/解组成定义的接口.

我编写了一个递归函数,遍历模板以构造一个字符串片段,其中包含要包含的每个节点的名称.

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, …
Run Code Online (Sandbox Code Playgroud)

string json go

5
推荐指数
1
解决办法
190
查看次数

标签 统计

go ×1

json ×1

string ×1