Skip to main content

The Language APIs Speak

APIs exchange data as JSON — text like {"id": 1, "name": "Ana"}. Go's encoding/json package translates in both directions: Marshal turns a struct into JSON, Unmarshal fills a struct from JSON.

Struct tags connect the two worlds: the tag `json:"name"` maps Go's exported Name field to the lowercase JSON key. Only exported fields (capital first letter) are translated at all.


From Struct to JSON

json.Marshal produces compact JSON for machines; json.MarshalIndent produces readable JSON for humans and logs. The omitempty tag option drops fields that hold their zero value.

Marshal, pretty and compact

Ana has no email, and omitempty removes the empty field from her JSON entirely. Ben's full record prints indented.

Prompt
Write a Go program with a User struct using json tags and omitempty on the email. Marshal a user without an email compactly, and a full user with MarshalIndent, printing both JSON results.
Output: Go program and captured output

From JSON to Struct

json.Unmarshal parses JSON into a struct you provide (as a pointer). Unknown JSON keys are simply ignored; missing keys leave the zero value. The returned error is the only signal that the JSON was bad — always check it.

Unmarshal and the ignored extra

The JSON carries an extra key that the struct does not have — no error, it is skipped. Broken JSON, on the other hand, returns a real error.

Prompt
Write a Go program that unmarshals a JSON string with an extra unknown key into a User struct, printing the filled struct, and then tries to unmarshal broken JSON and prints the error.
Output: Go program and captured output

Nested Data

Real API payloads nest: an order carries its user and a list of items. Structs inside structs and slices map to JSON objects and arrays automatically — no special handling needed.

An order with a user inside

The nested User struct becomes a nested JSON object, the items slice becomes a JSON array — the shape of the Go data is the shape of the JSON.

Prompt
Write a Go program with an Order struct containing an ID, a slice of item names and a nested User struct, all with json tags. Marshal one order with MarshalIndent and print it to show nested objects and arrays.
Output: Go program and captured output