Basics of JSON with GoLang - GeeksforGeeks

06 Jan, 2022
JSON is a widely used format for data interchange. Golang provides multiple encoding and decoding APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. 
Data Types: The default Golang data types for decoding and encoding JSON are as follows: 
bool for JSON booleans
float64 for JSON numbers
string for JSON strings
nil for JSON null
array as JSON array
map or struct as JSON Object
1. Encoding/Marshaling structs: The Marshal() function in package encoding/json is used to encode the data into JSON. 
Syntax: func Marshal(v interface{}) ([]byte, error)
Example: 
Go
// Golang program to illustrate the// concept of encoding using JSONpackage main    import (    "fmt"    "encoding/json")    // declaring a structtype Human struct{            // defining struct variables    Name string    Age int    Address string}    // main functionfunc main() {            // defining a struct instance    human1 := Human{"Ankit", 23, "New Delhi"}            // encoding human1 struct    // into json format    human_enc, err := json.Marshal(human1)            if err != nil {                    // if error is not nil        // print error        fmt.Println(err)    }            // as human_enc is in a byte array    // format, it needs to be     // converted into a string     fmt.Println(string(human_enc))            // converting slices from    // golang to JSON format            // defining an array    // of struct instance    human2 := []Human{        {Name: "Rahul", Age: 23, Address: "New Delhi"},        {Name: "Priyanshi", Age: 20, Address: "Pune"},        {Name: "Shivam", Age: 24, Address: "Bangalore"},    }            // encoding into JSON format    human2_enc, err := json.Marshal(human2)                 if err != nil {                // if error is not nil        // print error            fmt.Println(err)        }                // printing encoded array    fmt.Println()        fmt.Println(string(human2_enc))}
Output: 
{"Name":"Ankit", "Age":23, "Address":"New Delhi"}

[{"Name":"Rahul", "Age":23, "Address":"New Delhi"}, {"Name":"Priyanshi", "Age":20, "Address":"Pune"}, {"Name":"Shivam", "Age":24, "Address":"Bangalore"}]
2. Decoding/Unmarshaling structs: The Unmarshal() function in package encoding/json is used to unpack or decode the data from JSON to struct.  
Syntax: func Unmarshal(data []byte, v interface{}) error
Example: 
Go
// Golang program to illustrate the// concept of decoding using JSONpackage main    import (    "fmt"    "encoding/json")    // declaring a structtype Human struct{            // defining struct variables    Name string    Address string    Age int}    // main functionfunc main() {            // defining a struct instance    var human1 Human            // data in JSON format which    // is to be decoded    Data := []byte(`{        "Name": "Deeksha",          "Address": "Hyderabad",        "Age": 21    }`)            // decoding human1 struct    // from json format    err := json.Unmarshal(Data, &human1)            if err != nil {                    // if error is not nil        // print error            fmt.Println(err)    }            // printing details of    // decoded data     fmt.Println("Struct is:", human1)    fmt.Printf("%s lives in %s.\n", human1.Name, human1.Address)            // unmarshaling a JSON array    // to array type in Golang            // defining an array instance    // of struct type    var human2 []Human            // JSON array to be decoded    // to an array    Data2 := []byte(`    [        {"Name": "Vani", "Address": "Delhi", "Age": 21},        {"Name": "Rashi", "Address": "Noida", "Age": 24},        {"Name": "Rohit", "Address": "Pune", "Age": 25}    ]`)            // decoding JSON array to     // human2 array    err2 := json.Unmarshal(Data2, &human2)                if err2 != nil {                // if error is not nil        // print error            fmt.Println(err2)        }            // printing decoded array     // values one by one    for i := range human2{                fmt.Println(human2[i])    }}
Output:
Struct is: {Deeksha Hyderabad 21}
Deeksha lives in Hyderabad.
{Vani Delhi 21}
{Rashi Noida 24}
{Rohit Pune 25}
 
Akanksha_Rai
abhishek0719kadiyan
Go Language
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Strings in Golang
Time Durations in Golang
How to Parse JSON in Golang?
Structures in Golang
Defer Keyword in Golang
Modulo Operator (%) in C/C++ with Examples
Arrow operator -> in C/C++ with Examples
Differences between Procedural and Object Oriented Programming
Structures in C++
Top 10 Programming Languages to Learn in 2022