Created
February 9, 2018 11:56
-
-
Save piersy/b9934790a8892db1a603820c0c23e4a7 to your computer and use it in GitHub Desktop.
Marshal JSON in Golang using 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 ( | |
"encoding/json" | |
"fmt" | |
"regexp" | |
"time" | |
"unicode" | |
"unicode/utf8" | |
) | |
// Regexp definitions | |
var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) | |
var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) | |
type conventionalMarshaller struct { | |
Value interface{} | |
} | |
func (c conventionalMarshaller) MarshalJSON() ([]byte, error) { | |
marshalled, err := json.Marshal(c.Value) | |
converted := keyMatchRegex.ReplaceAllFunc( | |
marshalled, | |
func(match []byte) []byte { | |
// Empty keys are valid JSON, only lowercase if we do not have an | |
// empty key. | |
if len(match) > 2 { | |
// Decode first rune after the double quotes | |
r, width := utf8.DecodeRune(match[1:]) | |
r = unicode.ToLower(r) | |
utf8.EncodeRune(match[1:width+1], r) | |
} | |
return match | |
}, | |
) | |
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
Adapted from here - https://gist.github.com/Rican7/39a3dc10c1499384ca91 that gist shows snake case conversion, this handles lowerCamelCase.