简体   繁体   中英

Merging slices of structs

I'm attempting to merge two different json array's of structs together into one json blob (from separate pagination requests). I'm however, unable to merge them together:

package main

import (
  "encoding/json"
  "log"
)

func main() {
  superset := `[{"id": 1231, "name": "testing1"},{"id": 1235, "name": "testing2"}]`
  subset   := `[{"id": 1237, "name": "testing3"}]`

  s, _ := json.Marshal(superset)
  log.Printf(string(s))

  u, _ := json.Marshal(subset)
  log.Printf(string(u))

   for i := range s {
     u = append(u, s[i])
   }

   log.Printf(string(u))
}

However, that gives me really just the concatenation of them:

"[{\"id\": 1237, \"name\": \"testing3\"}]""[{\"id\": 1231, \"name\": \"testing1\"},{\"id\": 1235, \"name\": \"testing2\"}]"

I'm hoping for an output that looks like:

[{"id": 1237, "name": "testing3"},{"id": 1231, "name": "testing1"},{"id": 1235, "name": "testing2"}]

I feel like I'm missing something silly. Any help would be greatly appreciated. Thank you!

json.Marshal() marshals the given value into JSON (and returns it as a []byte ), so what you have in s and u are JSON texts holding your input JSON texts. Appending (concatenating) these 2 texts will not even result in valid JSON, obviously not what you want.

Your inputs are JSON texts, holding a JSON array. So what you should do is unmarshal your inputs into Go slices (of type []interface{} ), which you can append, then marshal the result back to JSON.

Something like this:

superset := `[{"id": 1231, "name": "testing1"},{"id": 1235, "name": "testing2"}]`
subset := `[{"id": 1237, "name": "testing3"}]`

var s1, s2 []interface{}

if err := json.Unmarshal([]byte(superset), &s1); err != nil {
    panic(err)
}
if err := json.Unmarshal([]byte(subset), &s2); err != nil {
    panic(err)
}

s2 = append(s2, s1...)

result, err := json.Marshal(s2)
if err != nil {
    panic(err)
}
fmt.Println(string(result))

This outputs (try it on the Go Playground ):

[{"id":1237,"name":"testing3"},{"id":1231,"name":"testing1"},{"id":1235,"name":"testing2"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM