SoFunction
Updated on 2025-03-05

Go language json encoding of camel to underscore, underscore to camel

1. Requirements

The default structure json of golang is transcoded, and it is all uppercase camel format generated based on field names. However, the most commonly used json format is lowercase camel or lowercase underscore. Therefore, we need a unified method to convert, and do not want to write json tags one by one, for example

package main

import (
 "encoding/json"
 "fmt"
)

func main() {
 type Person struct {
 HelloWold    string
 LightWeightBaby string
 }
 var a = Person{HelloWold: "chenqionghe", LightWeightBaby: "muscle"}
 res, _ := (a)
 ("%s", res)
}

Running results

{"HelloWold":"chenqionghe","LightWeightBaby":"muscle"}

The output json structure is capital camel, which is definitely very awkward. Of course, we set the output json field name by setting the json tag, for example

type Person struct {
 HelloWold    string `json:"hello_wold"`
 LightWeightBaby string `json:"light_weight_baby"`
}

But if there are a lot of fields, it will be too troublesome to set them one by one.

2. Realization

Golang's standard Json processes various data types by calling its type interface UnmarshalJSON decoding and MarshalJSON encoding for conversion, so we can encapsulate a json structure that is unified conversion underscore or a json structure that is unified conversion, and implement the MarshalJSON method to achieve the goal.

Implemented as follows

package jsonconv

import (
 "bytes"
 "encoding/json"
 "log"
 "regexp"
 "strconv"
 "strings"
 "unicode"
)

/************************************************ Underline json ***************************************/
type JsonSnakeCase struct {
 Value interface{}
}

func (c JsonSnakeCase) MarshalJSON() ([]byte, error) {
 // Regexp definitions
 var keyMatchRegex = (`\"(\w+)\":`)
 var wordBarrierRegex = (`(\w)([A-Z])`)
 marshalled, err := ()
 converted := (
 marshalled,
 func(match []byte) []byte {
  return ((
  match,
  []byte(`${1}_${2}`),
  ))
 },
 )
 return converted, err
}

/***************************************************************/
type JsonCamelCase struct {
 Value interface{}
}

func (c JsonCamelCase) MarshalJSON() ([]byte, error) {
 var keyMatchRegex = (`\"(\w+)\":`)
 marshalled, err := ()
 converted := (
 marshalled,
 func(match []byte) []byte {
  matchStr := string(match)
  key := matchStr[1 : len(matchStr)-2]
  resKey := Lcfirst(Case2Camel(key))
  return []byte(`"` + resKey + `":`)
 },
 )
 return converted, err
}

/************************************ Other Methods *********************************/
// Change to underline writingfunc Camel2Case(name string) string {
 buffer := NewBuffer()
 for i, r := range name {
 if (r) {
  if i != 0 {
  ('_')
  }
  ((r))
 } else {
  (r)
 }
 }
 return ()
}

// Change the underline writing method to the camel writing methodfunc Case2Camel(name string) string {
 name = (name, "_", " ", -1)
 name = (name)
 return (name, " ", "", -1)
}

// Capitalization of the initial letterfunc Ucfirst(str string) string {
 for i, v := range str {
 return string((v)) + str[i+1:]
 }
 return ""
}

// Lowercase of the first letterfunc Lcfirst(str string) string {
 for i, v := range str {
 return string((v)) + str[i+1:]
 }
 return ""
}

// Embedded, supports continuous writingtype Buffer struct {
 *
}

func NewBuffer() *Buffer {
 return &Buffer{Buffer: new()}
}

func (b *Buffer) Append(i interface{}) *Buffer {
 switch val := i.(type) {
 case int:
 ((val))
 case int64:
 ((val, 10))
 case uint:
 ((uint64(val), 10))
 case uint64:
 ((val, 10))
 case string:
 (val)
 case []byte:
 (val)
 case rune:
 (val)
 }
 return b
}

func (b *Buffer) append(s string) *Buffer {
 defer func() {
 if err := recover(); err != nil {
  ("******The memory is not enough!******")
 }
 }()
 (s)
 return b
}

III. Use

JsonSnakeCase Unified to Underscore json

Just wrap the object to output json

func main() {
 type Person struct {
 HelloWold    string
 LightWeightBaby string
 }
 var a = Person{HelloWold: "chenqionghe", LightWeightBaby: "muscle"}
 res, _ := ({a})
 ("%s", res)
}

The output is as follows

{"hello_wold":"chenqionghe","light_weight_baby":"muscle"}

JsonCamelCase Unified Camel json

The structure of the underlined label has been specified, and we can also convert it into a camel json uniformly.

func main() {
 type Person struct {
 HelloWold    string `json:"hello_wold"`
 LightWeightBaby string `json:"light_weight_baby"`
 }
 var a = Person{HelloWold: "chenqionghe", LightWeightBaby: "muscle"}
 res, _ := ({a})
 ("%s", res)
}

The output is as follows

{"helloWold":"chenqionghe","lightWeightBaby":"muscle"}

It is very convenient to solve the requirement of json unified transcoding format

This is the article about the implementation of Go language json encoding the implementation of Hump to Underline and Underline to Hump. For more related contents of Go Hump to Underline and Underline to Hump, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!