-
-
Save glassonion1/72687cae25086b4e2108527d692734d4 to your computer and use it in GitHub Desktop.
Marshal JSON in Golang using common lower-camel-case object key conventions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"regexp" | |
"time" | |
) | |
// Regexp definitions | |
var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) | |
var wordBarrierRegex = regexp.MustCompile(`([a-z_0-9]))([A-Z])`) | |
type conventionalMarshaller struct { | |
Value interface{} | |
} | |
func (self conventionalMarshaller) MarshalJSON() ([]byte, error) { | |
marshalled, err := json.Marshal(self.Value) | |
converted := keyMatchRegex.ReplaceAllFunc( | |
marshalled, | |
func(match []byte) []byte { | |
return bytes.ToLower(wordBarrierRegex.ReplaceAll( | |
match, | |
[]byte(`${1}_${2}`), | |
)) | |
}, | |
) | |
return converted, err | |
} | |
type exampleModel struct { | |
Title string | |
Description string | |
CreatedAt time.Time | |
UpdatedAt time.Time | |
IsActive bool | |
} | |
func main() { | |
model := exampleModel{ | |
Title: "Example Title", | |
Description: "whatever", | |
CreatedAt: time.Now(), | |
UpdatedAt: time.Now(), | |
IsActive: true, | |
} | |
encoded, _ := json.MarshalIndent(conventionalMarshaller{model}, "", " ") | |
fmt.Println(string(encoded)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment