Skip to content

Instantly share code, notes, and snippets.

@glassonion1
Forked from Rican7/conventional-json.go
Last active May 25, 2019 23:27
Show Gist options
  • Save glassonion1/72687cae25086b4e2108527d692734d4 to your computer and use it in GitHub Desktop.
Save glassonion1/72687cae25086b4e2108527d692734d4 to your computer and use it in GitHub Desktop.
Marshal JSON in Golang using common lower-camel-case object key conventions
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