An instance of golang JSON array splicing

Time:2021-11-23

Look at the code~


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

result:

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

Accordingly, if the array is of interface type, the same applies.

Supplement: go implements JSON array nesting

Reference package “encoding / JSON”“

Define the following structures


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 instance as follows


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

Parse Class6


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

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.