Skip to content

Instantly share code, notes, and snippets.

@clarkritchie
Last active June 5, 2024 16:44
Show Gist options
  • Save clarkritchie/e98791cfb06f6fcd22e40ddb2516376c to your computer and use it in GitHub Desktop.
Save clarkritchie/e98791cfb06f6fcd22e40ddb2516376c to your computer and use it in GitHub Desktop.
JSON Hints

How to map a field in a Go struct to camelCased JSON when using json.Marshal.

In this example, the struct field Number is output as someNumber, and Title is aTitle.

example

package main

import (
	"encoding/json"
	"fmt"
)

type Foo struct {
	Number int    `json:"someNumber"` // <----  this is called a "json hint"
	Title  string `json:"aTitle"`
}

func main() {
	foo_marshalled, _ := json.Marshal(Foo{Number: 1, Title: "test"})
	fmt.Printf("%v\n", string(foo_marshalled))
}

output

go run foo.go
{"someNumber":1,"aTitle":"test"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment