Trending Articles       10 Flutter Listview Examples       Flutter Custom Button Example       Flutter Audio Recording       Flutter 2.0 Autocomplete TextField       Current Location Google Maps

Golang JSON Encoding Decoding Example

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

  • bool for JSON booleans,
  • float64 for JSON numbers,
  • string for JSON strings, and
  • nil for JSON null

 

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

 

 

Execute at golang playgroung

 

Related

Convert Float to String in Golang example

 

Tags: Golang tutorial, JSON Enocode, Decode,


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

119 Views

Flutter Questions

Android Questions