Skip to content

Instantly share code, notes, and snippets.

@cokert
Last active December 12, 2019 14:23
Show Gist options
  • Save cokert/0146dc943770f66807944f3eb02f86e6 to your computer and use it in GitHub Desktop.
Save cokert/0146dc943770f66807944f3eb02f86e6 to your computer and use it in GitHub Desktop.
// "forked" from here, but fork button wasn't working, so copy/pated...
// https://gist.github.com/walm/e61b5e44b37a67c6eaa1e7c048ef7bf1
package main
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"time"
)
// 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 {
return bytes.ToLower(wordBarrierRegex.ReplaceAll(
match,
[]byte(`${1}_${2}`),
))
},
)
return converted, err
}
type exampleModel struct {
Title string
ABVExample string
Description string
CreatedAt time.Time
UpdatedAt time.Time
IsActive bool
}
func main() {
model := exampleModel{
Title: "Example Title",
ABVExample: "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