You need to export the User.name field so that the json package can see it. Rename the name field to Name.
Copypackage main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
Output:
Copy{"Name":"Frank"}
Answer from peterSO on Stack OverflowMholt
mholt.github.io › json-to-go
JSON-to-Go: Convert JSON to Go instantly
This tool instantly converts JSON into a Go type definition. Paste a JSON structure on the left and the equivalent Go type will be generated to the right, which you can paste into your program.
Top answer 1 of 2
564
You need to export the User.name field so that the json package can see it. Rename the name field to Name.
Copypackage main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
Output:
Copy{"Name":"Frank"}
2 of 2
14
You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:
Copypackage main
import (
"fmt"
"encoding/json"
)
type User struct {
name string
}
func (u *User) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Name string `json:"name"`
}{
Name: u.name,
})
}
func main() {
user := &User{name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
How do you guys convert a json response to go structs?
There are tools that can create a struct out of a json object. https://mholt.github.io/json-to-go/ More on reddit.com
A tool for generating structs based on json I have
https://mholt.github.io/json-to-go/ More on reddit.com
What is the best way to handle json in Golang?
If the json is highly unstructured the unmarshal to map[string]any. For unknown structs use json.RawMessage More on reddit.com
Converting an interface{} to a struct
Looks like you're describing tagged unions. There is an interresting answer on stackoverflow. This is ideal if the content is a child field and the type is on top level, you can just unmarshal the child once you know the type and avoid too much unmarshalling. Still a bit more parsing overhead than the customConverter solution, benchmarking will decide if parsing once to primitives is more expensive than parsing twice the child payload. the following comes from stackoverflow https://stackoverflow.com/questions/55994888/unmarshal-json-tagged-union-in-go : type Request struct { RequestId string Inputs []struct { Intent string Payload json.RawMessage } } var request Request err := json.Unmarshal(j, &request) if err != nil { log.Fatalln("error:", err) } for _, input := range request.Inputs { var payload interface{} switch input.Intent { case "action.devices.EXECUTE": payload = new(Execute) case "action.devices.QUERY": payload = new(Query) } err := json.Unmarshal(input.Payload, payload) if err != nil { log.Fatalln("error:", err) } // Do stuff with payload } More on reddit.com
Videos
23:34
Understanding Go Structs for JSON Parsing - YouTube
04:07
JSON to GoLang Structs - YouTube
10:16
JSON Struct Tags in Go - YouTube
04:44
Go Golang decode unmarshal json string to struct - YouTube
05:14
JSON in Go: Encoding, Decoding & Struct Tags for Beginners - YouTube
04:42
golang reading json files to struct - YouTube
Go by Example
gobyexample.com › json
Go by Example: JSON
Go offers built-in support for JSON encoding and decoding, including to and from built-in and custom data types · We’ll use these two structs to demonstrate encoding and decoding of custom types below
The Trie Data Structure
drstearns.github.io › tutorials › gojson
Go Structs and JSON
How to encode structs into JSON and decode JSON into structs
Transform
transform.tools › json-to-go
JSON to Go Struct - Transform
to Go Struct · to GraphQL · to io-ts · to Java · to JSDoc · to JSON Schema · to Kotlin · to MobX-State-Tree Model · to Mongoose Schema · to MySQL · to React PropTypes · to Rust Serde · to Sarcastic · to Scala Case Class · to TOML · to TypeScript ·
GitHub
github.com › twpayne › go-jsonstruct
GitHub - twpayne/go-jsonstruct: Generate Go structs from multiple JSON or YAML objects. · GitHub
Handles JSON and YAML. Generates Go struct field names from camelCase, kebab-case, and snake_case object property names. Capitalizes common abbreviations (e.g. HTTP, ID, and URL) when generating Go struct field names to follow Go conventions, with the option to add your own abbreviations.
Starred by 363 users
Forked by 35 users
Languages Go
CodeSignal
codesignal.com › learn › courses › handling-json-in-go-1 › lessons › encoding-structs-into-json-in-go-1
Encoding Structs into JSON in Go
In this example, we define a Todo struct with fields Title, Done, and Description. Each field has a JSON tag that specifies the key name in the resulting JSON object. We create an instance of Todo and use json.Marshal to convert it into JSON. If successful, the JSON object is printed.
CodeSignal
codesignal.com › learn › courses › handling-json-in-go-1 › lessons › decoding-json-into-structs-in-go
Decoding JSON into Structs in Go
The struct tags (json:"title", etc.) map the JSON keys to Go struct fields. ... This function fetches JSON data from the given API URL and returns the raw JSON response body.
Reddit
reddit.com › r/golang › how do you guys convert a json response to go structs?
r/golang on Reddit: How do you guys convert a json response to go structs?
January 14, 2024 -
I have been practicing writing go for the last 20-25 days. I’m getting used to the syntax and everything. But, when integrating any api, the most difficult part is not making the api call. It is the creation of the response object as a go struct especially when the api response is big. Am I missing some tool that y’all been using?
Top answer 1 of 29
81
is json.Unmarshal not enough?
2 of 29
75
When the API response is large and you don't particularly care about the full contents you can simply create your struct and have it contain only the fields you care about. For example, suppose we only care about the firstName and lastName and we have the following response data: { "firstName": "John", "lastName": "Doe", "dob": "1990-01-01", "preferredName": "Johnny" } You can define the following struct and json.Unmarshal will do a best attempt at populating all of the fields. type person struct { FirstName string `json:"firstName,omitempty"` LastName string `json:"lastName,omitempty"` } You can then read the response into the struct by using the builtin json.Unmarshal var p person err := json.Unmarshal(resp, &p) // don't forget to check the error fmt.Println(p.FirstName) // prints "John" fmt.Println(p.LastName) // prints "Doe" For some reason the Go playground "share" feature isn't working so here's a main file you can build and run: package main import ( "encoding/json" "fmt" ) var resp = []byte(`{ "firstName": "John", "lastName": "Doe", "dob": "1990-01-01", "preferredName": "Johnny" }`) type person struct { FirstName string `json:"firstName,omitempty"` LastName string `json:"lastName,omitempty"` } func main() { var p person err := json.Unmarshal(resp, &p) if err != nil { panic(err) } fmt.Println(p.FirstName) // prints "John" fmt.Println(p.LastName) // prints "Doe" }
Go
go.dev › blog › json
JSON and Go - The Go Programming Language
Therefore only the exported fields of a struct will be present in the JSON output. To decode JSON data we use the Unmarshal function.
GitHub
gist.github.com › miguelmota › 04252b346d281b93f047bf9a20f73f04
Golang JSON Marshal (struct to string) (M for "Make json") and Unmarshal (string to struct) (U for "Unmake json") example · GitHub
Golang JSON Marshal (struct to string) (M for "Make json") and Unmarshal (string to struct) (U for "Unmake json") example - json_marshal_unmarshal.go
Medium
medium.com › @okesolakofo › generating-json-data-from-go-golang-structs-with-go2json-a013120d5d6
Generating JSON data from Go (Golang) structs with Go2JSON | by Kofo Okesola | Medium
February 5, 2022 - package maintype Example struct { Name string Address string Phone string Email string IntField int `json:"field_1"` StringField string Custom []CustomStruct CustomEmbedded struct { First string } `json:"embedded"` }type CustomStruct struct { Truthy bool ListString []string } To do this you would have probably had to painstakingly create and fill each field in your JSON by hand, or probably with a JSON editor like JsonEditor. ... GO2JSON initially started out as a way for me to explore the AST (abstract syntax tree) of Golang as well as potential code generation, but after a few frustrating JSON API endpoint testing for other projects, I turned it to GO2JSON.
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-struct-tags-in-go
How To Use Struct Tags in Go | DigitalOcean
March 24, 2026 - Learn how to use struct tags in Go for JSON, XML, database mapping, and validation. Includes syntax rules, reflection examples, and custom tag patterns.
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-json-in-go
How To Use JSON in Go | DigitalOcean
March 28, 2022 - While using a map[string]interface{} to marshal JSON data can be very flexible, it can also become a hassle if you need to send the same data in multiple places. If you copy this data to more than one place in your code, it can be easy to accidentally mistype a field name, or assign the incorrect data to a field. For times like these, it can be beneficial to use a struct type to represent the data you’re converting to JSON.