JSON

JSON stands for JavaScript Object Notation which helpful for sending and receiving structure data over different network. Its plateform and language independent.

We use of json/encoding package to work in with JSON in Golang.

Consider a structure for students, here string literals after Name, Year and Numbers type is called tag fields

// Students structure
type Students struct {
	Name    string `json:"name"`
	Year    int    `json:"year"`
	Numbers []int  `json:"numbers,omitempty"`
}

Marshalling: Converts Go data structure into JSON byte slice.

data, err := json.Marshal(students)
if err != nil {
	log.Fatalf("Found error while marshalling: %s", err)
}

Unmarshalling: Decodes JSON and populate Go data structure

var s []Students
err = json.Unmarshal(data, &s)
if err != nil {
	log.Fatalf("Found error while Unmarshalling %s", err)
}

Program

package main

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

// Students strcuture
type Students struct {
	Name    string `json:"name"`
	Year    int    `json:"year"`
	Numbers []int  `json:"numbers,omitempty"`
}

func main() {

	var students = []Students{
		{Name: "Bhawani", Year: 30, Numbers: []int{10, 20, 30}},
		{Name: "Shanker", Year: 32, Numbers: []int{11, 21, 29}},
	}

	data, err := json.Marshal(students)
	if err != nil {
		log.Fatalf("Found error while marshalling: %s", err)
	}

	// Print data
	fmt.Printf("%s\n", data)

	// Use of json.MarshalIndent
	data, err = json.MarshalIndent(students, "", "    ")
	if err != nil {
		log.Fatalf("Found error while JSON marshalling: %s", err)
	}
	fmt.Printf("%s\n", data)

	// Unmarshall data
	var s []Students
	err = json.Unmarshal(data, &s)
	if err != nil {
		log.Fatalf("Found error while unmarshalling %s", err)
	}

	// Print s
	fmt.Println(s)
}

Output:

[{"name":"Bhawani","year":30,"numbers":[10,20,30]},{"name":"Shanker","year":32,"numbers":[11,21,29]}]
[
    {
        "name": "Bhawani",
        "year": 30,
        "numbers": [
            10,
            20,
            30
        ]
    },
    {
        "name": "Shanker",
        "year": 32,
        "numbers": [
            11,
            21,
            29
        ]
    }
]
[{Bhawani 30 [10 20 30]} {Shanker 32 [11 21 29]}]

Leave a Reply

Your email address will not be published. Required fields are marked *