Home > Enterprise >  Create slice of integers from JSON array
Create slice of integers from JSON array

Time:11-27

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}

CodePudding user response:

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

  •  Tags:  
  • go
  • Related