从JSON数组创建整数切片

huangapple go评论87阅读模式
英文:

Create slice of integers from JSON array

问题

我正在尝试找出如何创建一个切片,以便更容易地操作和使用其中的值,以便稍后迭代并进行多个API请求。这个切片包含整数类型的API ID。在获取JSON数组ID之后,我成功地创建了一个包含自定义类型的结构体,但现在我需要从该JSON数组中仅提取值,并将它们转储到一个不包含键"id"的切片中(该键可能随时间变化而改变大小)。

这是我的JSON:

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

我希望从中得到以下结果:

{38926, 38927}
英文:

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}

</details>


# 答案1
**得分**: 3

如果您想要自定义解组行为,您需要一个具有自己的`json.Unmarshaler`的自定义类型,例如:

```go
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
}

要使用它,请在您的结构体中引用此类型,例如:

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

var d data

工作示例:https://go.dev/play/p/i3MAy85nr4X

英文:

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:&quot;id&quot;`
	}{}

	err := json.Unmarshal(data, &amp;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:&quot;data&quot;`
}

var d data

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

huangapple
  • 本文由 发表于 2021年11月27日 07:51:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/70131044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定