liveBook · Manning

Json.Unmarshal

As explained in Go in Action, Second Edition

json.Unmarshal is a Go standard-library function that decodes JSON data into a supplied Go value.

json.Unmarshal decodes a JSON byte slice into a supplied Go value, commonly a pointer to a configuration struct. It checks JSON-to-Go type compatibility and returns an error for malformed or incompatible input. section 10.5.1

Use json.Unmarshal effectively by combining it with:

  • Exported struct fields and JSON tags, which map JSON keys such as "port" to Go fields such as Port. section 10.5.1
  • Pointers to destination values, allowing decoded data to populate an existing struct. section 10.5.1
  • Custom UnmarshalJSON methods, which can reuse json.Unmarshal and add domain validation such as checking a host URL. section 10.5.1
  • An intermediate Go struct when converting JSON to another representation, so parsing validates and normalizes the data first. section 10.5.2

Decode a server configuration

Given JSON containing name, version, debug, port, and host fields, define a tagged Config struct and call json.Unmarshal(data, &cfg). Handle the returned error before using cfg; custom unmarshaling can reject an invalid host URL. section 10.5.1

Listing 10.16 config.json: Configuration defined in JSON format
{
    "name": "myapp",
    "version": "1.0.0",
    "debug": false,
    "port": 8080,
    "host": "localhost"
}

Inspect a concrete configuration payload containing strings, a Boolean, and an integer before mapping it into Go. section 10.5.1

How Go in Action, Second Edition covers it

How deep it goes
Explains destination pointers, struct tags, type checking, nested decoding, and custom validation without detailing the decoder implementation.
Examples
Demonstrates server configuration JSON, tagged Config values, custom host validation, and JSON-to-XML conversion.
What it assumes
Assumes familiarity with Go structs and pointers; establishes exported fields and JSON tags as decoding requirements.
What you can do after
Apply it via encoding/json to decode configuration data, detect input errors, and feed validated values into conversion workflows.
How it connects
Connects JSON decoding with Go structs, struct tags, validation, custom unmarshaling, marshaling, and XML conversion.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.