SoFunction
Updated on 2025-03-03

Go data structure to JSON

In daily work, in addition to the data structure that needs to be converted from JSON to Go. But often the opposite is: we need to send data to the web server as a JSON string. Today we will learn how to encode a structured data into JSON.

Json (Javascript Object Nanotation) is a data exchange format, often used for front-end and back-end data transmission. Any end converts the data into a json string, and the other end parses the string into the corresponding data structure, such as string type, strcut object, etc.

Convert structure to JSON format

For example, we have the following structure:

type Student struct {
    Name string
    Age int
    Address Address
}

type Address struct {
    Road string
    Street string
    City string
    Province string
    Country string
}

Zhang3 := Student{
        Name: "Zhang San",
        Age:  18,
        Address: Address{
            Road:     "renmin south road",
            Street:   "123 street",
            City:     "cs",
            Province: "hn",
            Country:  "CN",
        },
    }

To encode students into JSON format, we can use the () function in the JSON package:

Info_of_Zhang3, err := (Zhang3)
if err == nil {
    (string(Info_of_Zhang3))
} else {
    (err)
    return
}

The Marshal() function returns the encoded JSON (byte slice) and error information (if an error occurs). Then we can print the JSON string.
The complete code is as follows:

package main

import (
    "encoding/json"
    "fmt"
)

type Student struct {
    Name    string
    Age     int
    Address Address
}

type Address struct {
    Road     string
    Street   string
    City     string
    Province string
    Country  string
}

func main() {

    Zhang3 := Student{
        Name: "Zhang San",
        Age:  18,
        Address: Address{
            Road:     "renmin south road",
            Street:   "123 street",
            City:     "cs",
            Province: "hn",
            Country:  "CN",
        },
    }

    Info_of_Zhang3, err := (Zhang3)
    if err == nil {
        (string(Info_of_Zhang3))
    } else {
        (err)
        return
    }

}

Run the code and get the following JSON data result:

$ go run
{"Name":"Zhang San","Age":18,"Address":{"Road":"renmin south road","Street":"123 street","City":"cs","Province":"hn","Country":"CN"}}

When you look at the JSON output, you may have noticed that there is no indentation. If you want to indent the output and format it well, you can use the json.MarshalIndent() function.
For example, use the following statement:

Info_of_Zhang3, err := (Zhang3, "", "    ")

Function parsing: The second parameter specifies the beginning of each line output. At the beginning of the output, the third parameter specifies the string to be indented for each line. At this time (Zhang3, "", "    ") you can get the following output:

{
    "Name": "Zhang San",
    "Age": 18,
    "Address": {
        "Road": "renmin south road",
        "Street": "123 street",
        "City": "cs",
        "Province": "hn",
        "Country": "CN"
    }
}

Convert the interface to JSON format

Sometimes you don't want to fix the number of fields in the structure. Instead, you want to be able to add extra data when needed. You can do this using an empty interface, like so:

type Student map[string] interface{}
type Address map[string] interface{}

Using an empty interface, you can create your own Student variable and add the desired elements, like this:

Zhang3 := Student{
    "Name": "Zhang San",
    "Age": 18,
    "Address": Address{
        "Road": "renmin south road",
        "Street": "123 street",
        "City": "cs",
        "Province": "hn",
        "Country": "CN",
    },
    "Year": 2022,    // New school year}

The complete code is as follows:

package main

import (
    "encoding/json"
    "fmt"
)

type Student map[string]interface{}
type Address map[string]interface{}

func main() {
    Zhang3 := Student{
        "Name": "Zhang San",
        "Age":  18,
        "Address": Address{
            "Road":     "renmin south road",
            "Street":   "123 street",
            "City":     "cs",
            "Province": "hn",
            "Country":  "CN",
        },
        "Year":       2022, // New school year        "GraduateAt": 2026, // Graduation year    }

    InfoOfZhang3, err := (Zhang3, "", "    ")
    if err == nil {
        (string(InfoOfZhang3))
    } else {
        (err)
    }
}

The output result of the code is:

{
    "Address": {
        "City": "cs",
        "Country": "CN",
        "Province": "hn",
        "Road": "renmin south road",
        "Street": "123 street"
    },
    "Age": 18,
    "GraduateAt": 2026,
    "Name": "Zhang San",
    "Year": 2022
}

At the same time, we can see that the order of keys in the output JSON is sorted alphabetically.

Prototype of Marshal() function

Let's take a look at the Marshal function:

func Marshal(v interface{}) ([]byte, error) {
   e := newEncodeState()

   err := (v, encOpts{escapeHTML: true})
   if err != nil {
      return nil, err
   }
   buf := append([]byte(nil), ()...)

   ()
   (e)

   return buf, nil
}

The function can receive any type of interface data v and convert it to byte array type. The return value is JSON data and error information; if the conversion is successful, err == nil;
In the process of converting objects to JSON, the following principles will be followed:
a. The Boolean type is still a Boolean type after being converted to JSON;
b. The floating point type is converted to a regular number inside JSON;
c. The string will be converted into a Unicode string with UTF-8 encoding, escaped special characters;
d. Arrays and slices are converted to arrays in JSON, []byte class will be converted to base64 encoded strings, and the zero value of slice is converted to null;
e. Convert the structure to a JSON object, and only variables in the structure must be capitalized in the first letter to be converted to output by the exported fields, and these fields will be indexed as strings of the JSON object;
f. When converting a data structure of map type, the type of the data must be when map[string]T, T can be any type supported by the encoding/json package.

Summarize

This article simply converts common structures and interfaces in Go into JSON data, and other types are similar. Finally, the encoded function Marshal() prototype is given and a brief explanation is given.

In addition, the encoding/json package also provides Encode() and Decode() functions for format conversion of a single object, while the Marshal() and Unmarshal() functions work on multiple objects and byte streams.

In fact, this article simply introduces the simple conversion of Go language and JSON data in the console. When subsequent articles introduce file reading and writing, you can learn to deal with JSON files. Stay tuned!

This is the end of this article about Go to JSON. For more related Go to JSON content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!