How to Convert Snake Case Keys to Camel Case in Go JSON?

DDD
Release: 2024-10-28 12:07:01
Original
737 people have browsed it

How to Convert Snake Case Keys to Camel Case in Go JSON?

Converting Snake Case Keys in JSON to Camel Case in Go

Question:

In Go, how can we convert snake_case keys in a JSON to camelCase keys recursively? This is particularly relevant for aligning API response JSON with internal standards while receiving data from a datastore like Elasticsearch, where key formats may vary.

Answer:

To achieve this conversion, we can leverage several approaches. One effective method utilizes Go 1.8's feature of defining two structs with distinct field tags. By carefully crafting the tags, we can effortlessly convert between the two structs, effectively applying the desired key conversion.

Code Example Using Tags:

<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>
Copy after login

Recursive Map-Based Approach:

Another comprehensive strategy involves attempting to unmarshal the JSON document into a map. If the operation succeeds, we can methodically correct the keys and recursively execute the key conversion function for each map value. The following example illustrates how to convert all keys to uppercase. The fixKey function should be replaced with a snake_case conversion function in your implementation.

<code class="go">package main

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

func main() {
    // Document source as returned by Elasticsearch
    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>
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!