使用jsonapi的元帅切片

I have a slice of structs and I want to marshal it using https://github.com/google/jsonapi.

With a single struct, everything works fine. I simply pass a pointer as a second argument.

package main

import (
    "fmt"
    "os"

    "github.com/google/jsonapi"
)

type Spider struct {
    ID       int `jsonapi:"primary,spiders"`
    EyeCount int `jsonapi:"attr,eye_count"`
}

func main() {
    jsonapi.MarshalPayload(os.Stdout, &Spider{ID: 2, EyeCount: 12})
    // {"data":{"type":"spiders","id":"2","attributes":{"eye_count":12}}}
}

However, when I'm trying to do the same with a slice, things are quite different.

First of all, I'm converting my slice to a slice of pointers to those structs (don't know what else to do here, passing pointer to the slice didn't work).

spiders := []Spider{Spider{ID: 1, EyeCount: 8}, Spider{ID: 2, EyeCount: 12}}

var spiderPointers []*Spider
for _, x := range spiders {
    spiderPointers = append(spiderPointers, &x)
}
jsonapi.MarshalPayload(os.Stdout, spiderPointers)

It works. Sort of. Here is the issue:

{"data":[
  {"type":"spiders","id":"2","attributes":{"eye_count":12}},
  {"type":"spiders","id":"2","attributes":{"eye_count":12}}]}

The last element is repeated and it replaces other elements.

In the end, I came up with a somewhat working solution:

spiders := []Spider{Spider{ID: 1, EyeCount: 8}, Spider{ID: 2, EyeCount: 12}}
var spiderPointers []interface{}
for _, x := range spiders {
    var spider Spider
    spider = x
    spiderPointers = append(spiderPointers, &spider)
}

jsonapi.MarshalPayload(os.Stdout, spiderPointers)
// {"data":[{"type":"spiders","id":"1","attributes":{"eye_count":8}},
//          {"type":"spiders","id":"2","attributes":{"eye_count":12}}]}

But I'm sure there must be a better way, hence this question.

Why not that way [either3]?

var spiders interface{}
db.Model(spiders).Select()
jsonapi.MarshalPayload(os.Stdout, spiders)

Curious would you be able to use something like this??

package main

import (
    "encoding/json"
    "fmt"
    "os"

    "github.com/google/jsonapi"
)

type Spider struct {
    ID       int `jsonapi:"primary,spiders"`
    EyeCount int `jsonapi:"attr,eye_count"`
}

func main() {
    // spiders is a slice of interfaces.. they can be unmarshalled back to spiders later if the need arises
    // you don't need a loop to create pointers either... so better in memory usage and a bit cleaner to read.. you can in theory load the []interface{} with a for loop as well since you mentioned getting this data from a db
    var spiders []interface{}
    spiders = append(spiders, &Spider{ID: 1, EyeCount: 8}, &Spider{ID: 2, EyeCount: 12})
    fmt.Println("jsonapi, MarshalPayload")
    jsonapi.MarshalPayload(os.Stdout, spiders)

    // test against marshall indent for sanity checking
    b, _ := json.MarshalIndent(spiders, "", " ")
    fmt.Println("marshall indent")
    fmt.Println(string(b))
}