dskpywvki951583595 2017-10-27 15:53
浏览 1018

将json中的所有snake_case键转换为camel

In Golang, how can we convert snake_case keys in a JSON to camelCase ones recursively?

I am writing one http api in golang. This api fetches data from datastore, does some computation and return the response as JSON.

Situation is that the JSON document in the datastore (elasticsearch) is present with snake_case keys while the API response should be camelCase based (this is just to align with other api standard within project). The source which inserts into ES can't be modified. So its only at the api level keys conversion has to take place.

I have written a struct which is reading JSON from datastore nicely. But how can I convert the keys to camlelCase in golang?

The JSON is can be nested and all keys has to be converted. The JSON is arbitrarily large. i.e. some keys are just mapped to type interface{}

I am also using go's echo framework for writing the api.

Ex.

{
"is_modified" : true,
   { attribute": 
     {
      "legacy_id" : 12345 
     }
   }
}

TO

{
"isModified" : true,
   { attribute": 
     {
      "legacyId" : 12345 
     }
   }
}

Any pointers on how to do this in golang?

Thanks.

Struct:

type data_in_es struct {
IsModified bool `json:"is_modified,omitempty"`
Attribute *attribute `json:"attribute,omitempty"`
}

type attribute struct {
    LegacyId int `json:"legacy_id,omitempty"`
}
  • 写回答

1条回答 默认 最新

  • dongwei7245 2017-10-27 16:23
    关注

    Since Go 1.8 you can define two structs that only differ in their tags and trivially convert between the two:

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

    https://play.golang.org/p/dcBkkX9zQR

    To do this generically, attempt to unmarshal the JSON document into a map. If it succeeds, fix all the keys and recursively call your function for each value in the map. The example below shows how to convert all keys to upper case. Replace fixKey with the snake_case conversion function.

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

    https://play.golang.org/p/QQZPMGKrlg

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog