Go JSON programs turn Go structs into JSON text and turn JSON text back into Go values, which is how almost every Go API talks to browsers, mobile apps and other services. In this post, you will write fourteen JSON programs with their exact output, and each one explains its logic in the code comments. We end with the JSON programs interviewers ask most, such as parsing an API response and summing values from it.
You should know structs and tags from our Go struct programs and files from our Go file programs. For the theory, read Go JSON encoding and decoding. All programs were tested on Go 1.27.
What are Go JSON Programs?
Go JSON programs use the encoding/json package. Marshalling turns a Go value into JSON bytes, and unmarshalling reads JSON bytes into a Go value. Struct tags like json:"name" decide the JSON field names.
Think of JSON as a shipping label that every system can read. Your Go struct is the parcel. Marshalling prints the label, and unmarshalling reads a label that someone else wrote and packs the parcel to match.
Why Go JSON Programs Matter
JSON is the common language of the web. For example, a REST API returns orders as JSON, a mobile app sends a login form as JSON and a config file is often JSON. So Go JSON programs are needed in nearly every backend job.
- APIs: send and receive request and response bodies.
- Configs: load settings from JSON files.
- Integrations: read data from payment, SMS and email services.
- Interviews: tags,
omitempty, unknown fields andmap[string]anyare common questions.
How Go JSON Programs Work
When you marshal, Go looks at each exported field, reads its tag, and writes a JSON key and value. When you unmarshal, Go matches each JSON key to a field by tag or name, ignoring case, and converts the value to the field type.

The table below shows how Go types map to JSON.
| Go type | JSON type | Example |
|---|---|---|
| string | string | “Asha” |
| int, float64 | number | 42, 99.5 |
| bool | true or false | true |
| struct | object | {“id”:1} |
| slice, array | array | [1,2,3] |
| map[string]T | object | {“pen”:10} |
| nil pointer, nil slice | null | null |
Basic Go JSON Programs
These first Go JSON programs marshal and unmarshal simple structs. If JSON is new to you, start with Program 1, which turns a plain list into JSON.
Program 1: Turn a List of Names into JSON
package main
import (
"encoding/json" // encoding/json turns Go values into JSON and back
"fmt" // fmt prints text on the screen
)
func main() {
// A slice is a list of values. Here it holds three names.
// := creates a new variable and stores the value in it.
names := []string{"Asha", "Ravi", "Meera"}
// json.Marshal turns the list into JSON.
// It returns the JSON as bytes, plus err (the error value, nil if all went well).
data, err := json.Marshal(names)
if err != nil {
fmt.Println("error:", err)
return
}
// string() turns the bytes into text we can print.
fmt.Println(string(data))
}
["Asha","Ravi","Meera"]
First, you build a normal Go list of names. Then json.Marshal turns it into a JSON array with square brackets and quotes. Finally, string(data) makes the bytes printable.
Program 2: Marshal a Struct to JSON
package main
import (
"encoding/json"
"fmt"
)
// Product is one item in a shop.
// Tags set the JSON names. Without them, JSON would use "ID", "Name" and so on.
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
}
func main() {
product := Product{ID: 7, Name: "Notebook", Price: 45.5}
// Marshal returns JSON as a byte slice plus an error.
data, err := json.Marshal(product)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(string(data))
}
{"id":7,"name":"Notebook","price":45.5}
json.Marshal walks through each field of the struct. Only exported fields (capital first letter) are marshalled. The tag text after json: becomes the key.
Program 3: Pretty Print with MarshalIndent
package main
import (
"encoding/json"
"fmt"
)
// User has a name and a list of roles.
type User struct {
Name string `json:"name"`
Roles []string `json:"roles"`
}
func main() {
user := User{Name: "Ravi", Roles: []string{"admin", "editor"}}
// The second argument is a prefix for each line, the third is the indent (two spaces).
data, _ := json.MarshalIndent(user, "", " ") // the _ ignores the error to keep it short
fmt.Println(string(data))
}
{
"name": "Ravi",
"roles": [
"admin",
"editor"
]
}
MarshalIndent works like Marshal, but it puts each value on its own line. Use it for logs and files people will read. APIs usually use plain Marshal, which is smaller.
Program 4: Read a Simple JSON Text
package main
import (
"encoding/json"
"fmt"
)
// Weather holds the two values we want from the JSON text.
type Weather struct {
City string `json:"city"`
Temperature int `json:"temp"` // the JSON key "temp" fills this field
}
func main() {
// Backticks make a raw string, so the double quotes inside need no escaping.
body := `{"city": "Pune", "temp": 31}`
var weather Weather // an empty Weather, ready to be filled
// Unmarshal reads the JSON and fills weather. & gives Unmarshal its address.
err := json.Unmarshal([]byte(body), &weather)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(weather.City, "is", weather.Temperature, "degrees today")
}
Pune is 31 degrees today
This is the reverse of Program 1. json.Unmarshal reads each JSON key and finds the field with the matching tag. So “temp” goes into Temperature, even though the names differ.
Program 5: Unmarshal JSON into a Struct
package main
import (
"encoding/json"
"fmt"
)
// Order is a shop order from a client.
type Order struct {
ID int `json:"id"`
Amount float64 `json:"amount"`
Paid bool `json:"paid"`
}
func main() {
body := []byte(`{"id": 501, "amount": 1299.0, "paid": true, "coupon": "DIWALI"}`)
var order Order
// Pass a pointer, so Unmarshal can fill the struct.
err := json.Unmarshal(body, &order)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("%+v\n", order) // %+v prints field names with their values
}
{ID:501 Amount:1299 Paid:true}
The extra “coupon” key is ignored, because Order has no matching field. You must pass &order, or Go cannot change your variable.
Tag Options in Go JSON Programs
In Go JSON programs, tags can do more than rename fields.
Program 6: omitempty, Skip and String Options
package main
import (
"encoding/json"
"fmt"
)
// Account shows three tag options.
type Account struct {
Email string `json:"email"`
Phone string `json:"phone,omitempty"` // left out when empty
Password string `json:"-"` // never in JSON
Balance int `json:"balance,string"` // number written as a string
}
func main() {
account := Account{Email: "asha@example.com", Password: "secret", Balance: 2500}
data, _ := json.Marshal(account)
fmt.Println(string(data))
}
{"email":"asha@example.com","balance":"2500"}
omitempty hides the empty phone, and - keeps the password out of the JSON completely. The string option is useful when another system expects numbers inside quotes.
Program 7: Nested Structs and Slices
package main
import (
"encoding/json"
"fmt"
)
// Item is one thing in the cart.
type Item struct {
Name string `json:"name"`
Quantity int `json:"qty"`
}
// Address is where the cart is shipped.
type Address struct {
City string `json:"city"`
}
// Cart holds a user, a list of items and a shipping address.
type Cart struct {
User string `json:"user"`
Items []Item `json:"items"`
Ship Address `json:"ship"`
}
func main() {
body := `{"user":"Meera","items":[{"name":"pen","qty":3},{"name":"bag","qty":1}],"ship":{"city":"Pune"}}`
var cart Cart
err := json.Unmarshal([]byte(body), &cart)
if err != nil {
fmt.Println(err)
return
}
// The JSON array became a Go slice, so we can loop over it with range.
total := 0
for _, item := range cart.Items {
total += item.Quantity
}
fmt.Println(cart.User, "ships to", cart.Ship.City, "with", total, "items")
}
Meera ships to Pune with 4 items
JSON objects become structs, and JSON arrays become slices. The loop then adds up the quantity of each item. Nesting works to any depth.
Flexible Go JSON Programs
Sometimes Go JSON programs do not know the JSON shape in advance.
Program 8: Unknown JSON into map[string]any
package main
import (
"encoding/json"
"fmt"
)
func main() {
body := `{"name":"Kiran","age":31,"skills":["go","sql"],"active":true}`
// any means "a value of any type", so this map can hold anything.
var data map[string]any
json.Unmarshal([]byte(body), &data)
// Every JSON number becomes float64 in a map[string]any.
// .(float64) is a type assertion: it says "I know this value is a float64".
age := data["age"].(float64)
skills := data["skills"].([]any) // a JSON array becomes []any
fmt.Println(data["name"], int(age), len(skills), data["active"])
// %T prints the type of a value.
fmt.Printf("%T %T\n", data["age"], data["skills"])
}
Kiran 31 2 true
float64 []interface {}
This is the most common JSON surprise: numbers come back as float64, and arrays as []any. Use type assertions, as in our Go interface programs, to read them.
Program 9: Stream JSON with json.Decoder
package main
import (
"encoding/json"
"fmt"
"strings"
)
// Event is one action a user took.
type Event struct {
Type string `json:"type"`
User string `json:"user"`
}
func main() {
// Many JSON objects, one per line, like a log file or HTTP stream.
stream := strings.NewReader(`{"type":"login","user":"asha"}
{"type":"buy","user":"ravi"}
{"type":"logout","user":"asha"}`)
decoder := json.NewDecoder(stream)
for decoder.More() { // More reports whether another value is waiting
var event Event
err := decoder.Decode(&event) // read the next JSON object
if err != nil {
fmt.Println("error:", err)
break
}
fmt.Println(event.User, "->", event.Type)
}
}
asha -> login
ravi -> buy
asha -> logout
The decoder reads one JSON object on each Decode call. It works with any io.Reader, such as a file or an HTTP request body. Because it reads one value at a time, it handles big streams with little memory.
Program 10: Reject Unknown Fields
package main
import (
"encoding/json"
"fmt"
"strings"
)
// Signup is the only data we accept in a sign-up request.
type Signup struct {
Email string `json:"email"`
}
func main() {
body := `{"email":"a@b.com","isAdmin":true}`
decoder := json.NewDecoder(strings.NewReader(body))
decoder.DisallowUnknownFields() // fail instead of silently ignoring extra keys
var signup Signup
err := decoder.Decode(&signup)
fmt.Println(err)
}
json: unknown field "isAdmin"
DisallowUnknownFields makes the decoder strict. So the extra “isAdmin” key causes an error instead of being skipped. This protects APIs from typos and from clients sending fields you never expected.
Program 11: Custom MarshalJSON for Money
package main
import (
"encoding/json"
"fmt"
)
// Rupees stores money in paise to avoid float errors.
type Rupees int64
// MarshalJSON decides exactly how Rupees look in JSON.
func (amount Rupees) MarshalJSON() ([]byte, error) {
rupees := amount / 100 // whole rupees
paise := amount % 100 // % gives the remainder, the paise part
// %02d always prints two digits, so 5 paise becomes "05".
text := fmt.Sprintf(`"Rs %d.%02d"`, rupees, paise)
return []byte(text), nil
}
// Invoice has an ID and a total amount.
type Invoice struct {
ID int `json:"id"`
Total Rupees `json:"total"`
}
func main() {
data, _ := json.Marshal(Invoice{ID: 9, Total: 149950})
fmt.Println(string(data))
}
{"id":9,"total":"Rs 1499.50"}
When json.Marshal reaches the Total field, it calls our MarshalJSON method. The method splits the amount into rupees and paise and builds a quoted string. There is also UnmarshalJSON for the reverse direction.
Most Asked Interview Go JSON Programs
These Go JSON programs are the ones interviewers ask most.
Program 12: Parse an API Response and Sum Values
package main
import (
"encoding/json"
"fmt"
)
// Sale is one product and how much it sold.
type Sale struct {
Product string `json:"product"`
Sales float64 `json:"sales"`
}
// APIResponse is the full JSON reply from the server.
type APIResponse struct {
Status string `json:"status"`
Data []Sale `json:"data"`
}
func main() {
body := `{"status":"ok","data":[
{"product":"pen","sales":1200.5},
{"product":"book","sales":3400},
{"product":"bag","sales":899.5}]}`
var response APIResponse
err := json.Unmarshal([]byte(body), &response)
if err != nil {
fmt.Println("bad JSON:", err)
return
}
// Loop over the data slice, add up sales and remember the best seller.
total := 0.0
best := ""
bestSales := -1.0
for _, sale := range response.Data {
total += sale.Sales
if sale.Sales > bestSales {
bestSales = sale.Sales
best = sale.Product
}
}
fmt.Printf("status=%s total=%.2f best=%s\n", response.Status, total, best)
}
status=ok total=5500.00 best=book
First, Unmarshal fills the response struct, including the list of sales. Then the loop adds each sale to total. It also keeps the product with the highest sales, which is the book.
Program 13: Handle Bad JSON Gracefully
package main
import (
"encoding/json"
"errors"
"fmt"
)
// Config holds the server port.
type Config struct {
Port int `json:"port"`
}
func main() {
inputs := []string{`{"port": 8080}`, `{"port": "8080"}`, `{"port": 8080`}
for _, input := range inputs {
var config Config
err := json.Unmarshal([]byte(input), &config)
// errors.As checks the kind of error and fills these variables.
var typeErr *json.UnmarshalTypeError // a value had the wrong type
var syntaxErr *json.SyntaxError // the JSON text itself is broken
switch {
case err == nil:
fmt.Println("ok, port", config.Port)
case errors.As(err, &typeErr):
fmt.Println("wrong type for field", typeErr.Field)
case errors.As(err, &syntaxErr):
fmt.Println("syntax error:", err)
default:
fmt.Println("other error:", err)
}
}
}
ok, port 8080
wrong type for field port
syntax error: unexpected end of JSON input
The second input sends the port as text, so Go returns an UnmarshalTypeError. The third input is cut off, so Go returns a SyntaxError. Checking the error type lets an API return a helpful message to the client.
Program 14: Convert a Map to Sorted JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
stock := map[string]int{"pen": 40, "bag": 5, "book": 12}
// encoding/json sorts map keys, so the output is always the same.
data, _ := json.Marshal(stock)
fmt.Println(string(data))
// Round trip: JSON back to a map.
var back map[string]int
json.Unmarshal(data, &back)
fmt.Println(back["book"], len(back))
}
{"bag":5,"book":12,"pen":40}
12 3
Unlike printing a map with a range loop, json.Marshal always sorts map keys. That makes JSON output stable for tests and caches.
Struct vs map[string]any in Go JSON Programs
Go JSON programs can decode JSON into a struct or into a generic map. The diagram and table below compare them.
![Go JSON programs comparison of structs and map[string]any](https://smitabharat.com/blog/wp-content/uploads/2026/10/go-json-programs-diagram-2-1024x640.png)
| Feature | Struct | map[string]any |
|---|---|---|
| Know the shape first | Yes | No |
| Type safety | Checked by the compiler | Needs type assertions |
| Numbers | Your chosen type | Always float64 |
| Code readability | High | Low, many assertions |
| Best for | APIs you control or document | Unknown or changing JSON |
So use structs whenever you can, and fall back to map[string]any only for truly unknown data.
Common Mistakes in Go JSON Programs
- Lower case fields: unexported fields never appear in JSON, so start them with a capital letter.
- Passing a value to Unmarshal: you must pass a pointer, such as
&order. - Expecting ints from map[string]any: JSON numbers become
float64. - Ignoring errors: bad JSON leaves your struct half filled, so always check
err. - Leaking secrets: add
json:"-"to passwords and tokens.
Best Practices for Go JSON Programs
- Always use tags, so JSON names stay stable even if you rename Go fields.
- Use json.Decoder for HTTP bodies and files, since it reads from a stream.
- Turn on DisallowUnknownFields for strict APIs.
- Store money as integers, and format it in a custom
MarshalJSONif needed. - Use omitempty for optional fields, so responses stay small.
Go JSON Programs Interview Questions and Answers
Interviewers ask these Go JSON programs more than any other JSON questions. Each program is complete, with real output from Go 1.27.
Marshal and Tag Questions
Q1. What does this program print?
package main
import (
"encoding/json"
"fmt"
)
// Person has one field without a tag, one unexported field and one optional field.
type Person struct {
Name string
age int // lower case, so it is unexported
Email string `json:"email,omitempty"`
}
func main() {
data, _ := json.Marshal(Person{Name: "Asha", age: 30})
fmt.Println(string(data))
}
{"Name":"Asha"}
Name has no tag, so its JSON key is “Name”. The unexported age is skipped, and the empty Email is left out by omitempty.
Q2. What does this program print?
package main
import (
"encoding/json"
"fmt"
)
// Box has two lists, one with omitempty.
type Box struct {
Items []string `json:"items"`
Tags []string `json:"tags,omitempty"`
}
func main() {
nilItems, _ := json.Marshal(Box{}) // Items is nil
emptyItems, _ := json.Marshal(Box{Items: []string{}}) // Items is an empty list
fmt.Println(string(nilItems))
fmt.Println(string(emptyItems))
}
{"items":null}
{"items":[]}
A nil slice becomes null, while an empty slice becomes []. Front-end developers often prefer [], so set empty slices on purpose.
Q3. Does Unmarshal match keys case-sensitively?
No. If no exact match exists, Go matches keys to field names or tags ignoring case. So “EMAIL” fills a field tagged json:"email". Use exact names anyway, because other languages may be stricter.
Unmarshal Questions in Go JSON Programs
Q4. What does this program print?
package main
import (
"encoding/json"
"fmt"
)
// Profile uses a pointer, so "missing" and "zero" look different.
type Profile struct {
Age *int `json:"age"` // *int is a pointer to an int, or nil
}
func main() {
var missing, zero Profile
json.Unmarshal([]byte(`{}`), &missing)
json.Unmarshal([]byte(`{"age":0}`), &zero)
fmt.Println(missing.Age == nil, *zero.Age) // *zero.Age reads the int the pointer points to
}
true 0
A pointer field tells “missing” (nil) apart from “sent as 0”. This is the same idea as in our Go pointer programs.
Q5. What does this program print?
package main
import (
"encoding/json"
"fmt"
)
func main() {
good := json.Valid([]byte(`{"a":1}`)) // Valid only checks the JSON, it does not decode it
bad := json.Valid([]byte(`{a:1}`))
fmt.Println(good, bad)
}
true false
JSON keys must be in double quotes, so {a:1} is not valid JSON. json.Valid is a quick check before you decode.
Q6. What does this program print?
package main
import (
"encoding/json"
"fmt"
)
func main() {
var value any
json.Unmarshal([]byte(`12345678901234567890`), &value)
fmt.Printf("%T %v\n", value, value) // %T is the type, %v is the value
}
float64 1.2345678901234567e+19
Big numbers lose precision as float64. For IDs like this, use dec.UseNumber() or decode into a string or int64 field.
Q7. What does this program print?
package main
import (
"encoding/json"
"fmt"
)
func main() {
var numbers []int
err := json.Unmarshal([]byte(`[1, 2, 3]`), &numbers)
fmt.Println(numbers, err)
}
[1 2 3] <nil>
A JSON array decodes straight into a Go slice. The error is <nil>, which means it worked.
Output and Design Questions
Q8. What does this program print?
package main
import (
"encoding/json"
"fmt"
)
// Base holds fields shared by many types.
type Base struct {
ID int `json:"id"`
}
// Employee embeds Base, so it gets the ID field too.
type Employee struct {
Base
Name string `json:"name"`
}
func main() {
employee := Employee{Base: Base{ID: 1}, Name: "Dev"}
data, _ := json.Marshal(employee)
fmt.Println(string(data))
}
{"id":1,"name":"Dev"}
Fields of an embedded struct are flattened into the outer JSON object, just like promoted fields in Go.
Q9. What does this program print?
package main
import (
"encoding/json"
"fmt"
)
func main() {
data, _ := json.Marshal("<b>Go & JSON</b>")
fmt.Println(string(data))
}
"\u003cb\u003eGo \u0026 JSON\u003c/b\u003e"
By default, Go escapes <, > and & so the JSON is safe inside HTML. Use a json.Encoder with SetEscapeHTML(false) if you do not want this.
Q10. What is json.RawMessage used for?
It keeps part of the JSON as raw bytes, without decoding it. This is useful when one field’s shape depends on another field, such as a “type” field that tells you how to decode “payload” later.
Q11. What is the difference between json.Unmarshal and json.NewDecoder?
Unmarshal works on a byte slice you already have in memory. NewDecoder reads from an io.Reader, such as an HTTP body or a file, and can decode many values one after another.
Q12. How do you send JSON in an HTTP response?
Set the Content-Type header to application/json, then call json.NewEncoder(w).Encode(value). The encoder writes straight to the response, so you do not need a separate byte slice.
Practice Task
This task combines several Go JSON programs from above. Write a program that reads a JSON list of employees with name, department and salary, then prints the total salary for each department in sorted order. Hint: unmarshal into a slice of structs, add salaries into a map[string]int, then sort the keys.
Official Resources
Quick Recap
- Go JSON programs use
json.Marshalto write JSON andjson.Unmarshalto read it. - Struct tags control names, and
omitemptyand-hide fields. - Unknown JSON goes into
map[string]any, where numbers becomefloat64. json.Decoderstreams JSON from files and HTTP bodies with little memory.- Check errors with
errors.Asto give clients clear messages about bad JSON.
What’s Next?
Next, we start running code at the same time. Read Go goroutine programs with output, with WaitGroup and the famous odd-even printing program. For the theory, see the Go JSON guide.


