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

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

Mary-Kate Olsen
Release: 2024-10-28 17:07:29
Original
660 people have browsed it

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

Converting Snake-Case to CamelCase Keys in JSON

In Go, converting keys in a JSON document from snake_case to camelCase can be challenging, especially when the JSON is nested and may contain arbitrarily large or interface{} types.

Method 1: Using Different Structs with Tags

For simple conversion cases, you can leverage Go's ability to define different structs with varying tags. Unmarshal the JSON into the source struct with snake_case tags, then trivially convert it to the target struct with camelCase tags.

<code class="go">import (
    "encoding/json"
)

// Source struct with snake_case tags
type ESModel struct {
    AB string `json:"a_b"`
}

// Target struct with camelCase tags
type APIModel struct {
    AB string `json:"aB"`
}

func ConvertKeys(json []byte) []byte {
    var x ESModel
    json.Unmarshal(b, &x)

    b, _ = json.MarshalIndent(APIModel(x), "", "  ")
    return b
}</code>
Copy after login

Method 2: Recursively Converting Map Keys

For more complex JSON documents, you can attempt to unmarshal it into a map. If successful, recursively apply the key conversion function to all keys and values within the map.

<code class="go">import (
    "bytes"
    "encoding/json"
    "fmt"
    "strings"
)

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 to CamelCase Keys in JSON Using Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template