登录
首页 >  Golang >  Go问答

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

来源:Golang技术栈

时间:2023-03-09 09:51:16 290浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《如何将 json 对象的 json 数组合并到单个 json 对象》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到golang等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我需要合并对象的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"]}
    }
}

到这里,我们也就讲完了《如何将 json 对象的 json 数组合并到单个 json 对象》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于golang的知识点!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表