How to merge a json array of json objects to a single json object

若如初见. 提交于 2021-01-28 12:01:50

问题


I need to merge json array of objects such the values of same keys are appended Lets say I have an unknown json array like

"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"
    }
  ]

I want the result to be this way:

"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 "] 
}

回答1:


Using only the standard library, this should do the trick:

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"]}
    }
}


来源:https://stackoverflow.com/questions/64234626/how-to-merge-a-json-array-of-json-objects-to-a-single-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!