how to append or combine 2 []array golang beego

左心房为你撑大大i 提交于 2020-01-06 08:18:55

问题


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



来源:https://stackoverflow.com/questions/55234195/how-to-append-or-combine-2-array-golang-beego

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!