Table of Contents
✅ Marshal and Unmarshal of basic structures
✅ Marshal and Unmarshal that handle maps
✅ Process slices and arrays
✅ Ignore empty fields (using omitempty)
✅ Nested structure and custom field names
✅ Error handling suggestions
Summary: Key points
Home Backend Development Golang go by example json marshal and unmarshal

go by example json marshal and unmarshal

Jul 28, 2025 am 04:32 AM
json go

In Go, the encoding/json package is used to handle the serialization and deserialization of JSON. 1. Structural fields need to be accessed capitalized in the first letter. Set the key name through json:"name". Omitempty omits fields when the value is zero. json:"-" ignores fields; 2. Use json.Marshal to convert structure, map or slice to JSON string, and use json.Unmarshal to parse JSON data into variables; 3. When deserializing to interface{}, the number defaults to float64 type and needs to be converted through type assertions; 4. Nested structures can be serialized normally, and the embedded structure will be expanded; 5. Always check for errors in Marshal and Unmarshal. Common problems include JSON format errors, type mismatch, and non-exported fields. Correctly using struct tags and data structures can flexibly handle various JSON scenarios.

go by example json marshal and unmarshal

In the Go language, encoding/json package provides support for serialization (marshal) and deserialization (unmarshal) of JSON data. Here are a few common examples to demonstrate how to use json.Marshal and json.Unmarshal .

go by example json marshal and unmarshal

✅ Marshal and Unmarshal of basic structures

 package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Person struct {
    Name string `json:"name"`
    Age int `json:"age"`
    Email string `json:"email,omitempty"`
}

func main() {
    // Example 1: Marshal structure → JSON
    p := Person{
        Name: "Alice",
        Age: 30,
        Email: "alice@example.com",
    }

    data, err := json.Marshal(p)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Marshal result: %s\n", data)

    // Example 2: Unmarshal JSON → Structure jsonData := `{"name":"Bob","age":25,"email":"bob@example.com"}`
    var p2 Person
    err = json.Unmarshal([]byte(jsonData), &p2)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Unmarshal result: %v\n", p2)
}

Output:

 Marshal result: {"name":"Alice","age":30,"email":"alice@example.com"}
Unmarshal result: {Name:Bob Age:25 Email:bob@example.com}

Notice:

go by example json marshal and unmarshal
  • json:"name" specifies the key name of the field in JSON.
  • omitempty means that if the field is a zero value (such as empty string, 0, nil, etc.), it is omitted during serialization.

✅ Marshal and Unmarshal that handle maps

 // Marshal map → JSON
m := map[string]interface{}{
    "name": "Charlie",
    "age": 35,
    "tags": []string{"go", "dev"},
}
data, _ := json.Marshal(m)
fmt.Printf("Map to JSON: %s\n", data)

// Unmarshal JSON → map
var m2 map[string]interface{}
jsonData := `{"name":"David","age":28,"active":true}`
json.Unmarshal([]byte(jsonData), &m2)
fmt.Printf("JSON to map: %v\n", m2)

// Note: The number in the map resolves to float64 by default
if age, ok := m2["age"].(float64); ok {
    fmt.Println("Age:", int(age))
}

Output:

 Map to JSON: {"age":35,"name":"Charlie","tags":["go","dev"]}
JSON to map: map[age:28 name:David active:true]
Age: 28

⚠️ Note: When json.Unmarshal parses to interface{} , the number is float64 by default, and type assertion is required.

go by example json marshal and unmarshal

✅ Process slices and arrays

 people := []Person{
    {Name: "Alice", Age: 30},
    {Name: "Bob", Age: 25},
}

// Marshal slice
data, _ = json.Marshal(people)
fmt.Printf("Slice to JSON: %s\n", data)

// Unmarshal JSON array → slice
jsonData := `[{"name":"Eve","age":22},{"name":"Frank","age":33}]`
var people2 []Person
json.Unmarshal([]byte(jsonData), &people2)
fmt.Printf("JSON to slice: %v\n", people2)

Output:

 Slice to JSON: [{"name":"Alice","age":30},{"name":"Bob","age":25}]
JSON to slice: [{Name:Eve Age:22 Email:} {Name:Frank Age:33 Email:}]

✅ Ignore empty fields (using omitempty)

 p := Person{
    Name: "Grace",
    Age: 0, // Zero value// Leave blank in Email}

data, _ = json.Marshal(p)
fmt.Printf("With omitempty: %s\n", data)

Output:

 With omitempty: {"name":"Grace"}

Because Age is 0 (the zero value of int), but no omitempty , it will still output.
Email has omitempty and is empty, so it is omitted.

If you want to omit even the zero value, you can write it like this:

 Age int `json:"age,omitempty"`

✅ Nested structure and custom field names

 type Address struct {
    City string `json:"city"`
    Zip string `json:"zip"`
}

type User struct {
    Person `json:"person"` // Inline structure Address Address `json:"address"`
    Password string `json:"-"` // Not involved in serialization}

u := User{
    Person: Person{Name: "Helen", Age: 29},
    Address: Address{City: "Beijing", Zip: "100000"},
    Password: "secret123",
}

data, _ := json.Marshal(u)
fmt.Printf("Nested struct: %s\n", data)

Output:

 Nested struct: {"person":{"name":"Helen","age":29},"address":{"city":"Beijing","zip":"100000"}}
  • The embedded structure will be expanded.
  • json:"-" means that the field will not be serialized or deserialized.

✅ Error handling suggestions

When using json.Marshal and json.Unmarshal , always check for errors :

 data, err := json.Marshal(someValue)
if err != nil {
    log.Printf("Marshal error: %v", err)
    Return
}

err = json.Unmarshal(jsonData, &target)
if err != nil {
    log.Printf("Unmarshal error: %v", err)
    Return
}

Common errors include:

  • The JSON format is illegal
  • Type mismatch (as expected number but get string)
  • Fields cannot be exported (struct fields must be capitalized to be accessed by json packages)

Summary: Key points

  • Structure fields must be capitalized in the first letter to be accessed by json package.
  • Use json:"fieldName" to customize the key name.
  • omitempty can omit empty value fields.
  • json:"-" Ignore fields.
  • map[string]interface{} and []interface{} can be used for dynamic structures, but pay attention to type assertions.
  • The number is float64 by default in interface{} .

Basically that's it. In actual development, combining struct tag and reasonable data structures can flexibly handle most JSON scenarios.

The above is the detailed content of go by example json marshal and unmarshal. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1510
276
What are some best practices for logging in Go? What are some best practices for logging in Go? Aug 04, 2025 pm 04:48 PM

Using structured logging, adding context, controlling log levels, avoiding logging sensitive data, using consistent field names, correctly logging errors, taking into account performance, centrally monitoring logs and unifying configurations are best practices in Go to achieve efficient logging. First, structured logs in JSON format (such as using uber-go/zap or rs/zerolog) facilitate machine parsing and integrating ELK, Datadog and other tools; second, log traceability is enhanced by requesting context information such as ID and user ID, and can be injected through context.Context or HTTP middleware; third, use Debug, Info, Warn, Error levels reasonably, and operate through environment variables.

How to gracefully shut down a Go service? How to gracefully shut down a Go service? Aug 05, 2025 pm 08:21 PM

Usesignal.Notify()tolistenforSIGINT/SIGTERMandtriggershutdown;2.RuntheHTTPserverinagoroutineandblockuntilasignalisreceived;3.Callserver.Shutdown()withacontexttimeouttostopacceptingnewrequestsandallowin-flightonestocomplete;4.Propagatetheshutdownconte

How does a type implement an interface in Go? How does a type implement an interface in Go? Aug 03, 2025 pm 03:19 PM

InGo,atypeimplementsaninterfaceimplicitlybyprovidingallrequiredmethodswithoutexplicitdeclaration.1.Interfacesaresatisfiedautomaticallywhenatypehasmethodsmatchingtheinterface'ssignatureexactly.2.No"implements"keywordisneeded—ducktypingisused

How does JSON work with JavaScript? How does JSON work with JavaScript? Aug 04, 2025 am 01:58 AM

JSONworksseamlesslywithJavaScriptbecauseitoriginatedfromJavaScript'sobjectsyntax,makingitidealforwebapplications.1.JSONsyntaxmirrorsJavaScriptobjects,withtherequirementthatkeysandstringvaluesmustbeindoublequotes.2.JSON.parse()convertsaJSONstringintoa

How to parse XML data in Go How to parse XML data in Go Aug 05, 2025 pm 07:24 PM

Parsing XML data is very simple in Go, just use the built-in encoding/xml package. 1. Define a structure with xml tag to map XML elements and attributes, such as xml:"name" corresponding child elements, xml:"contact>email" handles nesting, xml:"id, attr" reads attributes; 2. Use xml.Unmarshal to parse XML strings into structures; 3. For files, use os.Open to open them and decode them through xml.NewDecoder, which is suitable for streaming processing of large files; 4. When processing duplicate elements, in the structure

How to get the current time in Go How to get the current time in Go Aug 06, 2025 am 11:28 AM

Usetime.Now()togetthecurrentlocaltimeasatime.Timeobject;2.FormatthetimeusingtheFormatmethodwithlayoutslike"2006-01-0215:04:05";3.GetUTCtimebycallingUTC()ontheresultoftime.Now();4.Extractcomponentslikeyear,month,dayusingmethodssuchasYear(),M

How to pretty print a JSON file in Python? How to pretty print a JSON file in Python? Aug 07, 2025 pm 12:10 PM

To beautify and print JSON files, you need to use the indent parameters of the json module. The specific steps are: 1. Use json.load() to read the JSON file data; 2. Use json.dump() and set indent to 4 or 2 to write to a new file, and then the formatted JSON file can be generated and the beautified printing can be completed.

How to stream data in Go? How to stream data in Go? Aug 03, 2025 am 11:30 AM

Use io.Reader and io.Writer to efficiently stream data to avoid memory overflow; use io.Copy to realize blocked transmission of files, HTTP or network data; use goroutines and channels to build processing pipelines, such as reading large log files line by line; use io.Pipe to safely transfer data between goroutines; always read and write in blocks to avoid loading all data at once, and ensure that memory is controllable.

See all articles