JSON in Go
Learn JSON in Go: structure, rules, marshaling, unmarshaling, error handling, validation, and deep cloning with encoding/json.
Introduction to JSON
JSON is a lightweight data-interchange format (key-value pairs, arrays, primitives). Go uses the encoding/json package to marshal (struct to JSON) and unmarshal (JSON to struct).
1. What is JSON?
Data format for communication.
JSON Data Types
JSON supports a limited set of types. Go maps them to string, number (float64), bool, nil, slice, and map[string]any.
1. Supported JSON Data Types
Allowed types in JSON.
JSON Syntax Rules
JSON is strict: keys and strings in double quotes, no trailing commas, no comments. Invalid JSON causes Unmarshal to return an error.
1. Important JSON Rules
Rules you must follow.
Converting Struct to JSON (Marshal)
json.Marshal converts a Go value to a JSON byte slice. Use struct tags to control field names. Use json.MarshalIndent for pretty output.
1. Basic json.Marshal
Convert struct to JSON bytes.
2. Pretty Printing (MarshalIndent)
Format JSON for readability.
Converting JSON to Struct (Unmarshal)
json.Unmarshal(data, &v) parses JSON into a struct or map. The second argument must be a pointer.
1. Basic json.Unmarshal
Convert JSON bytes to struct.
Handling Invalid JSON
json.Unmarshal returns an error on invalid JSON. Always check err before using the result.
1. Checking Unmarshal Error
Prevent panics and handle bad input.
Deep Cloning with JSON
Marshal then Unmarshal produces a deep copy of JSON-serializable data. Nested structs and maps are copied; the original is unchanged.
1. Deep Clone using Marshal + Unmarshal
Traditional deep clone for JSON-safe data.
Validating JSON
Validation means checking that a string parses as valid JSON. Business rules (e.g. required fields, types) are separate.
1. Basic Validation (try Unmarshal, check err)
Safest approach.
2. Validation vs Parsing
Valid JSON may still have wrong types.
3. Safe JSON Parse Helper
Return value and error without panic.