SoFunction
Updated on 2025-03-04

Golang json array stitching example

Look at the code ~

func main() {
    a := []byte(`{"Parents": [ "aaaaa", "bbbbbbb" ]}`)
    b := []byte(`{"Parents": [ "Gomez", "Moticia" ]}`)
    var arr []interface{}
    js, _ := (a)
    nodes, _ := ()
    p := nodes["Parents"]
    d := p.([]interface{})
    for _, v := range d {
        arr = append(arr, v)
    }
    js, _ = (b)
    nodes, _ = ()
    p = nodes["Parents"]
    d = p.([]interface{})
    for _, v := range d {
        arr = append(arr, v)
    }
    res := make(map[string]interface{})
    res["Parents"] = arr
    c, _ := (res)
    (string(c))
}

result:

{“Parents”:[“aaaaa”,”bbbbbbb”,”Gomez”,”Moticia”]}

Correspondingly, if the array has an interface type, it also applies.

Supplement: Go implements json array nesting

Quote package "encoding/json"

Define the following structure

type person struct {
 Name string  `json:"name"`
 Sex  string  `json:"sex"`
 Age  string  `json:"age"`
}
type test struct {
 Class int   `json:"class"`
 Person []person `json:"person"`
}

Create an example below

class6 := 
`{ "class":6,
 "person":[{
  "name":"wangha",
  "sex":"male",
  "age":"18"
 },
 {
  "name":"zhang",
  "sex":"female",
  "age":"16"
 }]
}`

Perform class6 analysis

var keys test
if err := ([]byte(class6), &keys);err != nil{
 (err)
}else {
 ("%+v\n", keys)
 ("%+v\n", [1])
 ("%s\n", [0].Sex)
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.