How to work with JSON data in Go?

How to work with JSON data in Go?

This article covers the encoding/json package which handles conversion between JSON and Go types (as per RFC 7159).

This article covers the encoding/json package which handles conversion between JSON and Go types (as per RFC 7159). Let's jump right in!

the code is available in this GitHub repo

Converting a Go type into JSON

Marshal

A common option is to use the Marshal function whose signature is:

    func Marshal(v interface{}) ([]byte, error)

Here is an example:

func main() {
    profile := Profile{Email: "[email protected]", Username: "abhirockzz", Blogs: []Blog{
        Blog{BlogName: "devto", URL: "https://dev.to/abhirockzz/"},
        Blog{BlogName: "medium", URL: "https://medium.com/@abhishek1987/"},
    }}
    jsonData, err := json.Marshal(&myprofile)
    //jsonData, err := json.MarshalIndent(&profile, "", " ")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(jsonData))
}

you can use MarshalIndent (commented) to indent the JSON output

Encoder

While Marshal deals in byte arrays ([]byte), an Encoder is generic and lets you work with an io.Writer which you can define to be the sink for JSON data i.e. you can specify any type which implements the io.Writer interface e.g. this could be standard out (os.Stdout), or an HTTP response (http.ResponseWriter), etc.

func main() {
    profile := Profile{Email: "[email protected]", Username: "abhirockzz", Blogs: []Blog{
        Blog{BlogName: "devto", URL: "https://dev.to/abhirockzz/"},
        Blog{BlogName: "medium", URL: "https://medium.com/@abhishek1987/"},
    }}

    encoder := json.NewEncoder(os.Stdout)
    err := encoder.Encode(&profile)
    if err != nil {
        panic(err)
    }
}

Use NewEncoder to specify the io.Writer. When you call Encode, the conversion takes place and the JSON is writer to io.Writer you specified.

Here is an example of how it would work with an HTTP response:

func main() {
    profile := Profile{Email: "[email protected]", Username: "abhirockzz", Blogs: []Blog{
        Blog{BlogName: "devto", URL: "https://dev.to/abhirockzz/"},
        Blog{BlogName: "medium", URL: "https://medium.com/@abhishek1987/"},
    }}

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        encoder := json.NewEncoder(w)
        err := encoder.Encode(&profile)
        if err != nil {
            panic(err)
        }
    })

    http.ListenAndServe(":8080", nil)
}

Converting JSON data to a Go type

Unmarshal

Given JSON in form of a byte array, Unmarshal stores the JSON parsing result to a pointer of the Go data type you specify (typically a struct)

func Unmarshal(data []byte, v interface{}) error

Here is a simple example:

func main() {
    jsonData := `{"email":"[email protected]","username":"abhirockzz","blogs":[{"name":"devto","url":"https://dev.to/abhirockzz/"},{"name":"medium","url":"https://medium.com/@abhishek1987/"}]}`

    var profile Profile
    err := json.Unmarshal([]byte(jsonData), &profile)
    if err != nil {
        panic(err)
    }
    ...
}

Decoder

Decoder provides a generic way of unmarshalling JSON data by allowing you to specify the source of JSON input in the form of an io.Reader as opposed to a byte array.

func main() {
    jsonData := `{"email":"[email protected]","username":"abhirockzz","blogs":[{"name":"devto","url":"https://dev.to/abhirockzz/"},{"name":"medium","url":"https://medium.com/@abhishek1987/"}]}`

    jsonDataReader := strings.NewReader(jsonData)
    decoder := json.NewDecoder(jsonDataReader)

    var profile Profile
    err := decoder.Decode(&profile)
    if err != nil {
        panic(err)
    }
    ...
}

We start by creating an io.Reader from the JSON string data using a shortcut strings.NewReader. We can then instantiate the decoder using NewDecoder and simply use decode with a pointer to the Profile struct to which the result is stored

go golang json javascript

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

How to work with JSON in Golang

In this article, I will show you the basics of how to parse and return JSON in Go while also providing you with an understanding of the process.

Javascript | How To Covert Javascript Array To JSON

In this example, we will see How To Covert Javascript Array To JSON. We can convert Javascript array to json using JSON.stringify() method. At some point in your time, whatever developer you are, you need to deal with JSON data. JSON stands for Javascript Object Notation. Exchange data between client and server is straightforward using JSON.

JavaScript | Convert JSON String to JSON Object

Convert JSON string to JSON object javascript. This tutorial is the purpose to explain the best ways and examples for convert JSON string to a JSON object.

Convert JSON To CSV In Golang with Example

The CSV package has a NewWriter() function that returns the Writer object which is used for writing the CSV data. The csv.Writer() writes csv records that are terminated by the newline and uses the comma as a field delimiter.