英文:
How to show map key and value of a struct inside a json
问题
你想将原始的JSON转换成包含"id"和"name"键的对象数组。你可以按照以下步骤进行转换:
- 创建一个空的对象数组。
- 遍历原始JSON中的每个键值对。
- 对于每个键值对,创建一个包含"id"和"name"键的对象,并将对应的值赋给它们。
- 将该对象添加到对象数组中。
- 最后,将对象数组转换为JSON格式。
以下是示例代码:
package main
import (
"encoding/json"
"fmt"
)
func main() {
originalJSON := `{
1: "games",
2: "technology",
3: "tekk",
4: "home entertainment",
5: "toys & stationery"
}`
var originalMap map[int]string
err := json.Unmarshal([]byte(originalJSON), &originalMap)
if err != nil {
panic(err)
}
var convertedArray []map[string]interface{}
for id, name := range originalMap {
obj := map[string]interface{}{
"id": id,
"name": name,
}
convertedArray = append(convertedArray, obj)
}
convertedJSON, err := json.Marshal(convertedArray)
if err != nil {
panic(err)
}
fmt.Println(string(convertedJSON))
}
运行以上代码,你将得到转换后的JSON字符串:
[{"id":1,"name":"games"},{"id":2,"name":"technology"},{"id":3,"name":"tekk"},{"id":4,"name":"home entertainment"},{"id":5,"name":"toys & stationery"}]
希望对你有帮助!
英文:
I've this piece of code.
package main
import (
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
func divisionsHandler(c *gin.Context) {
divisions := getDivisionRows()
json := make(map[int]string)
for divisions.Next() {
var d Division
err := divisions.Scan(&d.id, &d.name)
json[d.id] = d.name
if err != nil {
panic(err.Error())
}
}
c.JSON(200, json)
}
The result is
{
1: "games",
2: "technology",
3: "tekk",
4: "home entertainment",
5: "toys & stationery"
}
I am trying to convert that json in something like
{
[{
"id": 1,
"name": "games"
},
...
]
}
but how?
答案1
得分: 1
所以你想要一个 JSON 数组而不是一个 JSON 对象?
不要加载 map[int]string
,为什么不直接创建一个 []Division
?
list := []Division{}
for divisions.Next() {
var d Division
err := divisions.Scan(&d.id, &d.name)
list = append(list, d)
if err != nil {
panic(err.Error())
}
}
你需要将字段名称更改为 ID
和 Name
,以便 json 包可以对它们进行序列化,但你最终应该得到类似以下的结果:
[
{"ID":1,"Name":"Games"},
...
]
英文:
So you want a json array instead of a json object?
Instead of loading a map[int]string
, why not simply make a []Division
?
list := []Division{}
for divisions.Next() {
var d Division
err := divisions.Scan(&d.id, &d.name)
list = append(list, d)
if err != nil {
panic(err.Error())
}
}
You'll need to change the field names to ID
and Name
so that the json package can serialize them, but you should end up with somthing more like:
[
{"ID":1,"Name":"Games},
...
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论