0

I'm trying to figure out how to create a slice I can more easily manipulate and use JUST the values from to later iterate over to make a number of API requests. The slice of integers are API IDs. I am successfully making a struct with custom types after making a GET to retrieve the JSON Array of IDs, but I now need to pull only the values from that JSON array and dump them into a slice without the key "id" (which will likely need to change over time in size).

This is my JSON:

{
  "data": [
    {
      "id": 38926
    },
    {
      "id": 38927
    }
  ],
  "meta": {
    "pagination": {
      "total": 163795,
      "current_page": 3,
      "total_pages": 81898
    }
  }
}

And I would like this from it:

{38926, 38927}

1 Answer 1

3

If you want custom Unmarshaling behavior, you need a custom type with its own json.Unmarshaler e.g.

type ID int

func (i *ID) UnmarshalJSON(data []byte) error {
    id := struct {
        ID int `json:"id"`
    }{}

    err := json.Unmarshal(data, &id)
    if err != nil {
        return err
    }

    *i = ID(id.ID)

    return nil
}

To use this, reference this type in your struct e.g.

type data struct {
    IDs []ID `json:"data"`
}

var d data

working example: https://go.dev/play/p/i3MAy85nr4X

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.