-
-
Save Rican7/39a3dc10c1499384ca91 to your computer and use it in GitHub Desktop.
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)) | |
} |
How about "is_ur_l" for "IsURL" field? Or "is_ur_lactive" for "IsURLActive"?
I expected to have "is_url" and "is_url_active" respectively.
@bezigon Maybe that's also work.
(\w)([A-Z])
-> ([a-z_0-9])([A-Z])
This is actually outputting snake case, I've uploaded a gist giving lower camel case here https://gist.github.com/piersy/b9934790a8892db1a603820c0c23e4a7
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
and camelCase
transformations, among others. ๐
Thanks for the comments, suggestions, and forks on this original Gist everyone!
โ๏ธ /cc: @bezigon @edwardstudy @glassonion1 @piersy @JoeyBoolean
โ๏ธ /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 !
Output