首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在json中将键的值从int更改为string

如何在json中将键的值从int更改为string
EN

Stack Overflow用户
提问于 2022-11-03 05:25:38
回答 1查看 44关注 0票数 -1

在这个json中,我想在golang中将键的值从int更改为string。

输入:

代码语言:javascript
运行
复制
{
    "id": 12345,
    "wrapper": 898984,
    "sections": {
        "main": {
            "type": 76899
        }
    },
    "order": [
        82322
    ]
}

期望产出:

代码语言:javascript
运行
复制
{
    "id": "12345",
    "wrapper": "898984",
    "sections": {
        "main": {
            "type": "76899"
        }
    },
    "order": [
        "82322"
    ]
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-03 06:39:36

最简单的方法是为两个jsons创建结构。然后创建相互转换的函数:

代码语言:javascript
运行
复制
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/

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74298454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档