Home  >  Article  >  Backend Development  >  How can I convert JSON keys from snake_case to camelCase in Go?

How can I convert JSON keys from snake_case to camelCase in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 02:09:28491browse

How can I convert JSON keys from snake_case to camelCase in Go?

Converting JSON Snake Case Keys to Camel Case Keys

In Go, snake_case keys in a JSON object can be converted to camelCase keys recursively using techniques based on Go's data structures and JSON encoding/decoding functionality.

One approach involves defining two structs that differ only in their JSON tags, enabling easy conversion between them. The following code demonstrates this:

<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>

For more general conversion, an alternative method involves unmarshalling the JSON document into a map. If successful, key fixes can be applied and recursive calls made for each value in the map.

<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 {
            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>

The above is the detailed content of How can I convert JSON keys from snake_case to camelCase in 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