英文:
How to make array of objects that contains key-values in golang?
问题
假设我正在使用Go语言的for循环迭代一些数据。
for _, job := range orderJobs {}
在每次迭代中,我希望在数组中添加一个新的对象,该对象应包含键值对。
所以最终的输出应该类似于:
[
{
"order_id": "123",
"job_name": "JOB1"
},
{
"order_id": "456",
"job_name": "JOB2"
}
]
在这种情况下,我应该声明并使用Go的映射吗?如果是的话,我应该如何声明?
我尝试声明:
Jobs := make(map[string]interface{})
并在循环迭代中像下面这样插入键值对:
Jobs["order_id"] = "123"
但它没有达到创建对象数组的目的。
英文:
Let's say, I am iterating some data in go for loop.
for _, job := range orderJobs {}
for each iteration, I want a new object to be added in array and that object should contain the key value pairs.
So the final output should be something like
[
{
"order_id":"123"
"job_name":"JOB1"
}
{
"order_id":"456"
"job_name":"JOB2"
}
]
Should I declare and use go maps in this case ? If yes then how exactly I should declare ?
I tried declaring
Jobs := make(map[string]interface{})
and inserting key value pairs like below inside loop iteration
Jobs["order_id"] = "123"
it's not serving the purpose of creating array of objects.
答案1
得分: 4
声明一个切片变量jobs:
var jobs []map[string]any
在for循环中向切片中添加值:
jobs = append(jobs, map[string]any{"order_id": "123", "job_name":"JOB1"})
英文:
Declare jobs as a slice:
var jobs []map[string]any
Append values to the slice in the for loop:
jobs = append(jobs, map[string]any{"order_id": "123", "job_name":"JOB1"})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论