arrays - 如何将json对象的json数组合并到单个json对象

标签 arrays json go unmarshalling

我需要合并对象的json数组,以便附加相同键的值
可以说我有一个未知的json数组,例如

"jsonarray": [
    {
      "behavior": [
        "file",
        "create_doc_exe"
      ],
      "id": 3303511,
      "platform": "Windows 7 x64 SP1, Adobe Reader 11, Flash 11, Office 2010"
    },
    {
      "info": [
        "sign , 3c4e53e "
      ],
      "behavior": [
        "sys_folder",
        "file",
        "process",
        "crash"
      ],
      "id": 3303,
      "platform": "Windows XP, Adobe Reader 9.4.0, Flash 10, Office 2007"
    }
  ]
我希望结果是这样的:
"jsonarray": {
    "behavior": [
        "file",
        "create_doc_exe",
        "sys_folder",
        "file",
        "process",
        "crash"
    ], 
    "id": [3303511,3303], 
    "platform": [
        "Windows 7 x64 SP1, Adobe Reader 11, Flash 11, Office 2010",
        "Windows XP, Adobe Reader 9.4.0, Flash 10, Office 2007"
    ], 
    "info": ["sign , 3c4e53e "] 
}

最佳答案

仅使用标准库,这应该可以解决问题:

package main

import (
    "encoding/json"
    "fmt"
)

var content = `{
    "jsonarray": [
    {
      "behavior": [
        "file",
        "create_doc_exe"
      ],
      "id": 3303511,
      "platform": "Windows 7 x64 SP1, Adobe Reader 11, Flash 11, Office 2010"
    },
    {
      "info": [
        "sign , 3c4e53e "
      ],
      "behavior": [
        "sys_folder",
        "file",
        "process",
        "crash"
      ],
      "id": 3303,
      "platform": "Windows XP, Adobe Reader 9.4.0, Flash 10, Office 2007"
    }
  ]
}`

type payload struct {
    JSONArray []map[string]interface{} `json:"jsonarray"`
}

func main() {
    var objPayload = payload{
        []map[string]interface{}{},
    }

    if err := json.Unmarshal([]byte(content), &objPayload); err != nil {
        panic(err)
    }

    var result = map[string]interface{}{}

    for _, item := range objPayload.JSONArray {
        for k, v := range item {
            var ok bool

            // If this is the first time our key is brought up, let's just copy it to the final map
            if _, ok = result[k]; !ok {
                result[k] = v
                continue
            }

            // It's not the first time this key shows up, let's convert it to a slice if it's still not
            if _, ok = result[k].([]interface{}); !ok {
                result[k] = []interface{}{result[k]}
            }

            // Then let's ensure our value is also a slice
            if _, ok = v.([]interface{}); !ok {
                v = []interface{}{v}
            }

            // Appending it to the result
            result[k] = append(
                result[k].([]interface{}),
                v.([]interface{})...,
            )
        }
    }

    if resultBytes, err := json.Marshal(&result); err != nil {
        panic(err)
    } else {
        fmt.Printf("%s", resultBytes) //done!
        // Result should be {"behavior":["file","create_doc_exe","sys_folder","file","process","crash"],"id":[3303511,3303],"info":["sign , 3c4e53e "],"platform":["Windows 7 x64 SP1, Adobe Reader 11, Flash 11, Office 2010","Windows XP, Adobe Reader 9.4.0, Flash 10, Office 2007"]}
    }
}

关于arrays - 如何将json对象的json数组合并到单个json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64234626/

相关文章:

perl - 如何输出用引号括起来的每个 Perl 数组元素?

用于查找数组最大公共(public)子集的 Objective-C 算法?

javascript - 无法解析 JSON 字符串属性中存在的 XML

java - 如何使用 GSON 库将自由文本转换为 Java 中的 Json 字符串数组?

go - 去处理所有返回的错误是惯用的吗?

tensorflow - 我发现save_model.go中存在错误导入路径

javascript - 如何在 vuetify 中动态添加/删除带有选择/自动完成值的新表单行?

java - 在两个java程序之间交换 double 组的最快方法

javascript - knockout 映射——将多个数据源整合到一个 View 模型中

interface - 如何获取未知接口(interface)上的结构值{}