登录
首页 >  Golang >  Go问答

如何有效地更改 JSON 键

来源:stackoverflow

时间:2024-04-06 08:51:38 254浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《如何有效地更改 JSON 键》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

在输入处,程序接收一个 json。

我需要返回相同的 json,但使用 camelcase 键。

是否有任何有效的方法可以将 json 中的所有 snake_case 键转换为 go 中的 camelcase 键?

片段代码

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
    "regexp"
    "strings"
)

type CategoryList struct {
    Id   *string `json:"id"`
    Name *string `json:"name"`
}

type Data struct {
    AccessToken  *string         `json:"access_token"`
    Category     *string         `json:"category"`
    CategoryList []*CategoryList `json:"category_list"`
    Name         *string         `json:"name"`
    Id           *string         `json:"id"`
    Tasks        []*string       `json:"tasks"`
}

type Paging struct {
    Cursors *Cursors `json:"cursors"`
}

type Cursors struct {
    Before *string `json:"before"`
    After  *string `json:"after"`
}

type Categories struct {
    Data   []*Data `json:"data"`
    Paging *Paging `json:"paging"`
}

func main() {
    jsonString := `{"data":[{"access_token":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","category":"First Category","category_list":[{"id":"2301","name":"Finance App"}]},{"access_token":"ZYXWVUTSRQPONMLKJIHGFEDCBA","category":"Second Category","category_list":[{"id":"2302","name":"Medical App"}]}],"paging":{"cursors":{"before":"MTA0MjcxMzIxNjYxNTkz","after":"MTA3MTA5NDcxNDc5MTk3"}}}`

    var categories map[string]interface{}
    if err := json.Unmarshal([]byte(jsonString), &categories); err != nil {
        panic(err)
    }

    modified := fromSnakeCaseToCamelCase(reflect.ValueOf(categories))

    result, err := json.Marshal(modified.Interface().(map[string]interface{}))
    if err != nil {
        panic(err)
    }
    fmt.Println(string(result))
}

func fromSnakeCaseToCamelCase(value reflect.Value) reflect.Value {
    switch value.Kind() {
        case reflect.Array, reflect.Slice:
            for i := 0; i < value.Len(); i++ {
                nestedValue := value.Index(i)

                fromSnakeCaseToCamelCase(nestedValue)
            }
        case reflect.Map:
            for _, keyName := range value.MapKeys() {
                nestedValue := value.MapIndex(keyName)

                newKeyName := reflect.ValueOf(convertToCamelCase(keyName.Interface().(string)))
                value.SetMapIndex(newKeyName, nestedValue)

                oldKeyName := reflect.ValueOf(keyName.Interface().(string))
                value.SetMapIndex(oldKeyName, reflect.Value{})

                fromSnakeCaseToCamelCase(nestedValue)
            }
        default:
            // pass
    }
    return value
}

var link = regexp.MustCompile("(^[A-Za-z]|_[A-Za-z])")

func convertToCamelCase(str string) string {
    return link.ReplaceAllStringFunc(str, func(s string) string {
        r := strings.NewReplacer("_", "")
        return strings.ToUpper(r.Replace(s))
    })
}

正确答案


您可以将 JSON 解组为 interface{},这将为每个 JSON 对象生成一个 map[string]interface{}。递归遍历结构并根据需要替换键,然后再次将其封送回 JSON。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>