Home  >  Article  >  Backend Development  >  How to Convert Snake-Case Keys to CamelCase in JSON Using Go?

How to Convert Snake-Case Keys to CamelCase in JSON Using Go?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 13:12:02887browse

How to Convert Snake-Case Keys to CamelCase in JSON Using Go?

Converting Snake-Case Keys to CamelCase in JSON Using Go

If you're working with JSON data that uses snake_case keys and you need to convert them to camelCase, you can do so efficiently in Go. This guide demonstrates how to accomplish this task recursively.

Solution Using Different Struct Tags

Introduced in Go 1.8, you can create two structs that differ only in their JSON field tags. This allows for easy conversion between the two structs:

<code class="go">package main

import (
    "encoding/json"
    "fmt"
)

type ESModel struct {
    AB string `json:"a_b"`
}

type APIModel struct {
    AB string `json:"aB"`
}

func main() {
    b := []byte(`{ "a_b": "c" }`)

    var x ESModel
    json.Unmarshal(b, &x)

    b, _ = json.MarshalIndent(APIModel(x), "", "  ")
    fmt.Println(string(b))
}</code>

Recursive Solution for General Cases

If the JSON structure is more complex, you can use a recursive approach to convert the keys:

<code class="go">package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "strings"
)

func main() {
    b := json.RawMessage(`{
            "a_b": "c",
            "d_e": ["d"],
            "e_f": {
                    "g_h": {
                            "i_j": "k",
                            "l_m": {}
                    }
            }
    }`)

    x := convertKeys(b)

    buf := &bytes.Buffer{}
    json.Indent(buf, []byte(x), "", "  ")
    fmt.Println(buf.String())
}

func convertKeys(j json.RawMessage) json.RawMessage {
    m := make(map[string]json.RawMessage)
    if err := json.Unmarshal([]byte(j), &m); err != nil {
            // Not a JSON object
            return j
    }

    for k, v := range m {
            fixed := fixKey(k)
            delete(m, k)
            m[fixed] = convertKeys(v)
    }

    b, err := json.Marshal(m)
    if err != nil {
            return j
    }

    return json.RawMessage(b)
}

func fixKey(key string) string {
    return strings.ToUpper(key)
}</code>

In this solution, the convertKeys function recursively converts all the keys of a JSON map. Replace the fixKey function with your own version for converting snake_case to camelCase.

The above is the detailed content of How to Convert Snake-Case Keys to CamelCase in JSON Using Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn