Last active
November 27, 2023 07:10
-
-
Save Rican7/39a3dc10c1499384ca91 to your computer and use it in GitHub Desktop.
Marshal JSON in Golang using common lower-snake-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 ( | |
"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 | |
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)) | |
} |
☝️ /cc: @bezigon @edwardstudy @glassonion1 @piersy @JoeyBoolean
(re-doing this since people actually get notified now... https://help.github.com/en/articles/about-gists#receiving-notifications-for-gist-activity)
Nice, thx !
It works very well.
I just change your regex for (\w{2,})([A-Z])
.
I have interface with the key ID
and your regex transform this in i_d
If someone has a better way :)
@Nyura95 try checking out this project instead:
https://github.com/Rican7/conjson
It's an expansion on this idea. 😃
Nice ! Thank you for sharing !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Soooo, I know its been 3+ years and all, but I've turned this kind of behavior into a proper package:
https://github.com/Rican7/conjson
It incorporates both
snake_case
andcamelCase
transformations, among others. 😃Thanks for the comments, suggestions, and forks on this original Gist everyone!