SoFunction
Updated on 2025-03-05

Read and write operations of JSON files in Go language

JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy to read and write, and is also easy to machine parse and generate. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.

JSON is a plain text format encoded using UTF-8, using a completely language-independent text format. Because it is convenient to write than XML format, and requires less processing time, JSON format has become increasingly popular, especially in transmitting data over a network connection.

Developers can use JSON to transfer simple strings, numbers, and boolean values, or an array or a more complex composite structure. In the field of web development, JSON is widely used in data communication between web server programs and clients.

Go language has built-in support for JSON. Using the built-in encoding/json standard library, developers can easily use Go programs to generate and parse data in JSON format.

The JSON structure is as follows:

{"key1":"value1","key2":value2,"key3":["value3","value4","value5"]}

Write a JSON file

It is very convenient to create a json file using Go language, and the sample code is as follows:

package main
import (
    "encoding/json"
    "fmt"
    "os"
)
type Website struct {
    Name   string `xml:"name,attr"`
    Url    string
    Course []string
}
func main() {
    info := []Website{{"Golang", "/golang/", []string{"/cplus/", "/linux_tutorial/"}}, {"Java", "/java/", []string{"/socket/", "/python/"}}}
    // Create a file    filePtr, err := ("")
    if err != nil {
        ("File creation failed", ())
        return
    }
    defer ()
    // Create a Json encoder    encoder := (filePtr)
    err = (info)
    if err != nil {
        ("Coding Error", ())
    } else {
        ("Coding successfully")
    }
}

Running the above code will generate a file in the current directory, with the file contents as follows:

[
    {
        "Name":"Golang",
        "Url":"/golang/",
        "Course":[
            "/golang/102/",
            "/golang/concurrent/"
        ]
    },
    {
        "Name":"Java",
        "Url":"/java/",
        "Course":[
            "/java/10/",
            "/python/"
        ]
    }
]

Read JSON files

Reading JSON data is as simple as writing JSON data, the sample code is as follows:

package main
import (
    "encoding/json"
    "fmt"
    "os"
)
type Website struct {
    Name   string `xml:"name,attr"`
    Url    string
    Course []string
}
func main() {
    filePtr, err := ("./")
    if err != nil {
        ("File opening failed [Err:%s]", ())
        return
    }
    defer ()
    var info []Website
    // Create a json decoder    decoder := (filePtr)
    err = (&info)
    if err != nil {
        ("Decoding failed", ())
    } else {
        ("Decoding successfully")
        (info)
    }
}

The operation results are as follows:

go run
Decoding successfully
[{Golang /golang/ [/golang/102/ /golang/concurrent/]} {Java /java/ [/java/10/ /python/]}]

By the way, there is another format called BSON (Binary JSON) that is very similar to JSON. Compared with JSON, BSON focuses on improving storage and scanning efficiency. Large elements in BSON documents are prefixed with a length field for easy scanning. In some cases, BSON will use more space than JSON due to the existence of length prefixes and explicit array indexes.

This is the article about reading and writing operations of JSON files in Go. For more related Go JSON reading and writing content, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!