Cara menggabungkan array json objek json menjadi satu objek json

Saya perlu menggabungkan objek array json sehingga nilai kunci yang sama ditambahkan Katakanlah saya memiliki array json yang tidak diketahui seperti

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

Saya ingin hasilnya seperti ini:

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

person Rahul    schedule 06.10.2020    source sumber


Jawaban (1)


Hanya dengan menggunakan perpustakaan standar, ini akan berhasil:

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"]}
    }
}
person Gustavo Kawamoto    schedule 07.10.2020
comment
Bisakah kita memfilter nilai duplikat dalam array yang dihasilkan? Katakanlah hasilnya adalah {"behavior":["file","file","crash"],"id":[3303,3303],"info":["sign , 3c4e53e "],"platform":["Windows 7 x64 SP1"]} Setelah memfilter duplikat, seharusnya {"behavior":["file","crash"],"id":[3303],"info":["sign , 3c4e53e "],"platform":["Windows 7 x64 SP1"]} Kita dapat memanggil fungsi lain untuk menghapus duplikat tetapi itu akan mengakibatkan perulangan seluruh payload. Akan lebih efisien jika kita dapat memfilter duplikat tersebut di sini - person Rahul; 07.12.2020