JSON

Contents
Marshal structs
Unmarshal into structs
Field tags
Encode straight to a writer

Marshal structs

The encoding/json package converts Go values to JSON bytes and back. Marshal takes a struct, a slice, a map, or a plain value and returns JSON. Most programs start with Marshal because it shows exactly how Go sees your data. The program below keeps the Go field names, since no tags are set yet.

package main import ( "encoding/json" "fmt" ) type User struct { Name string Age int } func main() { user := User{Name: "Ada", Age: 36} data, err := json.Marshal(user) if err != nil { fmt.Println(err) return } fmt.Println(string(data)) }

go run main.go

{"Name":"Ada","Age":36}

Unmarshal into structs

Unmarshal parses JSON bytes into a value described by a Go type. Pass a pointer so the decoder can fill the struct in place. When the input does not match the target, Unmarshal returns an error instead of stopping the program. Always check that error before you trust the result.

package main import ( "encoding/json" "fmt" ) type User struct { Name string Age int } func main() { raw := []byte(`{"Name":"Ada","Age":36}`) var user User if err := json.Unmarshal(raw, &user); err != nil { fmt.Println(err) return } fmt.Println(user.Name, user.Age) }

Unknown fields in the input are ignored by default, and missing fields keep their zero values. That makes Unmarshal forgiving when a server adds new keys. Strict validation belongs in your own code after decoding.

Field tags

Struct tags rename fields and control what gets emitted. A tag is a small string after the field type, written in backticks. Use omitempty to drop zero values and a dash to skip a field completely. Tags keep secrets like tokens out of logs and responses.

package main import ( "encoding/json" "fmt" ) type User struct { Name string `json:"name"` Age int `json:"age,omitempty"` Token string `json:"-"` } func main() { user := User{Name: "Ada", Token: "secret"} data, err := json.Marshal(user) if err != nil { fmt.Println(err) return } fmt.Println(string(data)) }

{"name":"Ada"}

Age is zero here, so omitempty removes it, and the dash hides Token every time. Lowercase names in tags follow the usual JSON style. The Go field names stay exported with a capital letter so the package can see them.

Encode straight to a writer

Encoder writes JSON straight to a writer such as a file, a network connection, or standard output. There is no need to hold the whole document in memory first. Decoder does the reverse and reads values one by one from a reader. Streaming fits logs, exports, and long feeds of events.

package main import ( "encoding/json" "os" ) type Event struct { Kind string `json:"kind"` Code int `json:"code"` } func main() { events := []Event{{Kind: "start", Code: 1}, {Kind: "stop", Code: 2}} enc := json.NewEncoder(os.Stdout) for _, e := range events { if err := enc.Encode(e); err != nil { panic(err) } } }

{"kind":"start","code":1}
{"kind":"stop","code":2}

Next: Files and IO

Article author: Arthur Isaev

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: