在这个json中,我想在golang中将键的值从int更改为string。
输入:
{
"id": 12345,
"wrapper": 898984,
"sections": {
"main": {
"type": 76899
}
},
"order": [
82322
]
}期望产出:
{
"id": "12345",
"wrapper": "898984",
"sections": {
"main": {
"type": "76899"
}
},
"order": [
"82322"
]
}发布于 2022-11-03 06:39:36
最简单的方法是为两个jsons创建结构。然后创建相互转换的函数:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
var input = `{ "id": 12345, "wrapper": 898984, "sections": { "main": { "type": 76899 } }, "order": [ 82322 ] }`
type DataWithInts struct {
ID int `json:"id"`
Wrapper int `json:"wrapper"`
Sections struct {
Main struct {
Type int `json:"type"`
} `json:"main"`
} `json:"sections"`
Order []int `json:"order"`
}
type MainStringsData struct {
Type string `json:"type"`
}
type SectionsStringsData struct {
Main MainStringsData `json:"main"`
}
type DataWithStrings struct {
ID string `json:"id"`
Wrapper string `json:"wrapper"`
Sections SectionsStringsData `json:"sections"`
Order []string `json:"order"`
}
func GetDataWithStrings(data *DataWithInts) *DataWithStrings {
var order []string
for _, v := range data.Order {
order = append(order, strconv.Itoa(v))
}
return &DataWithStrings{
ID: strconv.Itoa(data.ID),
Wrapper: strconv.Itoa(data.Wrapper),
Sections: SectionsStringsData{
Main: MainStringsData{
Type: strconv.Itoa(data.Sections.Main.Type),
},
},
Order: order,
}
}
func main() {
var dataInts DataWithInts
err := json.Unmarshal([]byte(input), &dataInts)
if err != nil {
panic(err)
}
dataStrings := GetDataWithStrings(&dataInts)
jsonData, err := json.Marshal(dataStrings)
if err != nil {
panic(err)
}
fmt.Println(string(jsonData))
}更通用的方法可以使用直接的json解析或反射包。
要创建结构,可以使用以下站点:https://mholt.github.io/json-to-go/
https://stackoverflow.com/questions/74298454
复制相似问题