How to show map key and value of a struct inside a json

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

How to show map key and value of a struct inside a json

问题

你想将原始的JSON转换成包含"id"和"name"键的对象数组。你可以按照以下步骤进行转换:

  1. 创建一个空的对象数组。
  2. 遍历原始JSON中的每个键值对。
  3. 对于每个键值对,创建一个包含"id"和"name"键的对象,并将对应的值赋给它们。
  4. 将该对象添加到对象数组中。
  5. 最后,将对象数组转换为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())
    }
}

你需要将字段名称更改为 IDName,以便 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},
  ...
]

huangapple
  • 本文由 发表于 2017年8月3日 20:03:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/45483655.html
匿名

发表评论

匿名网友

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

确定