how to append or combine 2 []array golang beego

2019-08-21 08:11发布

问题:

I have an array like List of my data as JSON. //

[
  {
    "ID": 1,
    ....
    "ClosedAt": "nine"
  },
...
]

I want to combine 2 arrays like and I tried to append them. -combine -append

[
  {
    "ID": 1,
    ....
    "ClosedAt": "nine"
  },
  {
    "ID": 2,
    ....
    "ClosedAt": "nine"
  },
  {
    "ID": 3,
    ....
    "ClosedAt": "nine"
  },

...

  {
     "totalpage": 10,
  },
]

Controller

tickets, ptotal, err := models.GetAllTicket(query, fields, sortby, order, offset, limit)
if err != nil {
    i.Data["json"] = err.Error()
} else {
    i.Data["json"] = ptotal
    i.Data["json"] = tickets

}
i.ServeJSON()

Beego(golang) API return JSON

回答1:

import "encoding/json"

func Append(json1, json2 []byte) ([]byte, error) {
    jsonArray1 := []json.RawMessage{}
    err := json.Unmarshal(json1, &jsonArray1)
    if err != nil {
        return nil, err
    }
    jsonArray2 := []json.RawMessage{}
    err = json.Unmarshal(json2, &jsonArray2)
    if err != nil {
        return nil, err
    }
    jsonArray := append(jsonArray1, jsonArray2...)
    result, err := json.Marshal(jsonArray)
    if err != nil {
        return nil, err
    }
    return result, nil
}

Hope it's you want