Skip to content

Instantly share code, notes, and snippets.

@srph
Created August 10, 2018 22:10
Show Gist options
  • Save srph/634c9c57edaace86779e703c38467911 to your computer and use it in GitHub Desktop.
Save srph/634c9c57edaace86779e703c38467911 to your computer and use it in GitHub Desktop.
Go: PascalSnake (e.g., Hello_World) un/marshaller
package main
import (
"bytes"
"regexp"
"encoding/json"
)
type PascalSnakeMarshaller struct {
Value interface{}
}
var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`)
var pascalSnakeRegex = regexp.MustCompile("(?P<l>[a-z])_(?P<r>[A-Z])")
func (s PascalSnakeMarshaller) MarshalJSON() ([]byte, error) {
marshalled, err := json.Marshal(s.Value)
if err != nil {
return nil, err
}
converted := keyMatchRegex.ReplaceAllFunc(
marshalled,
func(match []byte) []byte {
return bytes.ToLower(pascalSnakeRegex.ReplaceAll(
match,
[]byte("${l}_${r}"),
))
},
)
return converted, nil
}
func (s *PascalSnakeMarshaller) UnmarshalJSON(data []byte) error {
m := make(map[string]interface{})
err := json.Unmarshal(data, &m)
if err != nil {
return err
}
s.Value = m
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment