In this source code example, we show how to convert array/slice to JSON in Golang.
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 an array/slice into a JSON
In the example, we transform a slice of structs into JSON format:
package main
import (
"encoding/json"
"fmt"
"log"
)
type Employee struct {
Id int
FirstName string
LastName string
Email string
}
func main() {
employees := []Employee{
{Id: 2, FirstName: "Amir", LastName: "Khan", Email: "Amir@gmail.com"},
{Id: 3, FirstName: "Lucy", LastName: "Smith", Email: "Smith@gmail.com"},
{Id: 4, FirstName: "David", LastName: "Brown", Email: "David@gmail.com"},
}
json_data2, err := json.Marshal(employees)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(json_data2))
}
Output:
[{"Id":2,"FirstName":"Amir","LastName":"Khan","Email":"Amir@gmail.com"},{"Id":3,"FirstName":"Lucy","LastName":"Smith","Email":"Smith@gmail.com"},{"Id":4,"FirstName":"David","LastName":"Brown","Email":"David@gmail.com"}]
The output can be pretty printed with the MarshalIndent function.
package main
import (
"encoding/json"
"fmt"
"log"
)
type Employee struct {
Id int
FirstName string
LastName string
Email string
}
func main() {
employees := []Employee{
{Id: 2, FirstName: "Amir", LastName: "Khan", Email: "Amir@gmail.com"},
{Id: 3, FirstName: "Lucy", LastName: "Smith", Email: "Smith@gmail.com"},
{Id: 4, FirstName: "David", LastName: "Brown", Email: "David@gmail.com"},
}
json_data2, err := json.MarshalIndent(employees, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(json_data2))
}
Output:
[
{
"Id": 2,
"FirstName": "Amir",
"LastName": "Khan",
"Email": "Amir@gmail.com"
},
{
"Id": 3,
"FirstName": "Lucy",
"LastName": "Smith",
"Email": "Smith@gmail.com"
},
{
"Id": 4,
"FirstName": "David",
"LastName": "Brown",
"Email": "David@gmail.com"
}
]
Comments
Post a Comment