如何使用Golang Gin处理可变输入的JSON数据?

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

How to process variable input JSON with Golang Gin

问题

我正在尝试使用Gin和Golang编写我的第一个应用程序。
有一个服务将一些变量的JSON数据发送到控制器。
输入数据如下:

{
"shipping": {
"address_id1": {..一些数据..},
"address_id2": {..一些数据..}
},
"items": {
"item_id1": {..一些数据..},
"item_id2": {..一些数据..}
}
}

所以,我不知道items的键,我需要遍历items数组。
如何在Gin中实现这个功能呢?
在PHP中,我会像这样遍历关联数组:

foreach ($_POST['shipping'] as $key => $value) {
..一些处理数据的逻辑..
}

换句话说,如何正确处理输入的数据?

英文:

I trying to write my first app on Gin with Golang
There is some service that post some variable JSON to controller
Input data like this:

{
  "shipping:{
    "address_id1": {..some data..},
    "address_id2": {..some data..}
  },
  "items": {
    "item_id1": {..some data..},
    "item_id2": {..some data..}
  }
}

So, I don't know items keys and I need to process through items array
How can I do it with Gin?
In PHP I will walk through associative array like

foreach ($_POST['shipping'] as $key => $value) {
  ..some logic with data..
}

In other words, how to work with input posted data correctly?

答案1

得分: 2

在Go-Gin中,我们可以使用Gin的上下文对象的**Bind()BindJSON()**方法来访问以JSON格式发布的数据。

当键值未知时,可以使用嵌套的映射。

type Shipping map[string]map[string]string
type Items map[string]map[string]string

type RequestPayload struct {
	Shipping Shipping `json:"shipping"`
	Items    Items    `json:"items"`
}

// 控制器
func ShippingController(ctx *gin.Context) {
	var request RequestPayload
	if err := ctx.BindJSON(&request); err != nil {
		panic(err)
	}

	for key, value := range request.Items {
		fmt.Println("The key : ", key)
		fmt.Println("The value : ", value)
	}
}

以上是要翻译的内容。

英文:

In Go-Gin we can use Bind() or BindJSON() of Gin's context object to access the data which is posted as JSON.

You can use a nested map when the keys are unknown.

type Shipping map[string]map[string]string
type Items map[string]map[string]string

type RequestPayload struct {
	Shipping Shipping `json:"shipping"`
	Items    Items    `json:"items"`
}

// controller
func ShippingController(ctx *gin.Context) {
	var request RequestPayload
	if err := ctx.BindJSON(&request); err != nil {
		panic(err)
	}

	for key, value := range request.Items {
		fmt.Println("The key : ", key)
		fmt.Println("The value : ", value)
	}

}

huangapple
  • 本文由 发表于 2023年4月25日 13:06:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76097775.html
匿名

发表评论

匿名网友

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

确定