In this golang tutorial we will cover how to use JSON in golang to encode decode json. in golang JSON support default data types like
JSON Encode Example
// Go offers built-in support for JSON encoding and
// decoding, including to and from built-in and custom
// data types.
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
type Student struct {
Name string
Subjects []string
Id int64 `json:"ref"`
Rank string // An unexported field is not encoded.
}
student := Student{
Name: "Johnson",
Subjects: []string{"English", "Mathmatics", "General Science"},
Id: 999,
Rank: "Distinction",
}
var jsonData []byte
jsonData, err := json.Marshal(student )
if err != nil {
log.Println(err)
}
fmt.Println(string(jsonData))
}
|
In the above example it will convert student struct data to JSON data
Output:
{"Name":"Johnson","Subjects":["English","Mathmatics","General Science"],"ref":999,"Rank":"Distinction"}
|
To make indentation to print json we need to use
It will print JSON data with indentation json.MarshalIndent(student,""," " )
{
"Name": "Johnson",
"Subjects": [
"English",
"Mathmatics",
"General Science"
],
"ref": 999,
"Rank": "Distinction"
}
|
Decode JSON to struct Example
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
type Student struct {
Name string
Subject []string
Id int64 `json:"ref"`
Rank string // An unexported field is not encoded.
}
jsonData := []byte(`
{
"Name": "Johnson",
"Subject": [
"English",
"Mathmatics",
"Social Science"
],
"Id": 999,
"Rank":"Top Rank"
}`)
var student Student
err := json.Unmarshal(jsonData, &student)
if err != nil {
log.Println(err)
}
fmt.Println(student.Name, student.Subject, student.Id)
}
|
Output:
Johnson [English Mathmatics Social Science] 0
|
Related
Convert Float to String in Golang example
Tags: Golang tutorial, JSON Enocode, Decode,
Article Contributed By :
|
|
|
|
947 Views |