Go - Convert JSON to an array/slice

In the previous source code example, we have seen how to convert Struct to JSON in Golang. In this source code example, we show how to convert JSON to an array/slice in Golang with an example.

JSON (JavaScript Object Notation) is a lightweight data interchange format.

In Golang, the encoding/json package implements the encoding and decoding of JSON.

Go - Convert JSON to an array/slice

In this source code example, we show how to convert JSON to an array/slice in Golang with an example:

package main

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

type Employee struct {
    Id         int
    FirstName       string
    LastName string
	Email string
}

func main() {

    var employees []Employee

    data2 := []byte(`
    [
        {"Id": 1, "FirstName": "Amir", "LastName": "Khan", "Email": "Amir@gmail.com"},
        {"Id": 2, "FirstName": "Lucy", "LastName": "Smith", "Email": "Smith@gmail.com"},
        {"Id": 3, "FirstName": "David", "LastName": "Brown", "Email": "David@gmail.com"}
    ]`)

    err2 := json.Unmarshal(data2, &employees)

    if err2 != nil {

        log.Fatal(err2)
    }

    for i := range employees {

        fmt.Println(employees[i])
    }
}

Output:

{1 Amir Khan Amir@gmail.com}
{2 Lucy Smith Smith@gmail.com}
{3 David Brown David@gmail.com}

Comments