Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Convert an array/slice into a JSON in Go (Golang)

Posted on January 18, 2023January 18, 2023 by admin

Table of Contents

  • Overview
  • Example

Overview

encoding/json package provides the Marshal function which can be used to convert a golang array or slice into a JSON string and vice versa.

Let’s see an example

Example

package main
import (
"encoding/json"
"fmt"
)
func main() {
a := make([]string, 2)
a[0] = "John"
a[1] = "Sam"
j, err := json.Marshal(a)
if err != nil {
fmt.Printf("Error: %s", err.Error())
} else {
fmt.Println(string(j))
}
}

Output

["John","Sam"]

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2023 Welcome To Golang By Example | Design: Web XP