Created
August 10, 2018 22:10
-
-
Save srph/634c9c57edaace86779e703c38467911 to your computer and use it in GitHub Desktop.
Go: PascalSnake (e.g., Hello_World) un/marshaller
This file contains hidden or 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" | |
"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