JSON, short for JavaScript Object Notation, is a format in which data is stored and transferred. It is easy for humans to understand and write and easy for computers to parse. JSON is often used in web applications and socket programming for transmission over networks.
To encode a JSON object in Go, the Marshal()
method is used. To decode the resulting JSON objects, the Unmarshal()
method is used.
package mainimport ("encoding/json""fmt")// Struct definedtype ShotExample struct {Name stringShot string}func main() {// Converting Integer to JSONintJson, err := json.Marshal(22)if err == nil {fmt.Println(string(intJson))} else {panic(err)}// Converting String to JSONstrJson, err := json.Marshal("Educative")if err == nil {fmt.Println(string(strJson))} else {panic(err)}// Declaring a mapmapVar := map[string]int{"num1": 1, "num2": 2}// Converting map to JSONmapJson, err := json.Marshal(mapVar)if err == nil {fmt.Println(string(mapJson))} else {panic(err)}// Declaring struct objectstructVar := ShotExample{Name: "Educative", Shot: "JSON"}// Converting map to JSONstructJson, err := json.Marshal(structVar)if err == nil {fmt.Println(string(structJson))} else {panic(err)}}
This example demonstrates some different data types being encoded into JSON objects. As can be seen, JSON can be used to encode individual data items, maps, and structs.
JSON objects need to be decoded before they are used for programming. To decode JSON objects in GO, you need to declare a container variable.
package mainimport ("encoding/json""fmt")// Defining structtype ShotExample struct {Name stringShot string}func main() {// Declaring map variablemapVar := map[string]int{"num1": 1, "num2": 2}// Converting to JSONmapJson, err := json.Marshal(mapVar)// Declaring container variable for decodingvar mapDecode map[string]interface{}// Converting JSON object to map in containererr = json.Unmarshal(mapJson, &mapDecode)if err == nil {fmt.Println(mapDecode)} else {panic(err)}// Declaring struct objectstructVar := ShotExample{Name: "Educative", Shot: "JSON"}// Converting struct to JSONstructJson, err := json.Marshal(structVar)// Declaring container variable for decodingvar structDecode ShotExample// Converting JSON object to struct in containererr = json.Unmarshal(structJson, &structDecode)if err == nil {fmt.Println(structDecode)} else {panic(err)}}
This example shows how a JSON object is decoded for use in Go Language. A map variable, mapDecode
, is declared with the value type defined as an interface
to allow for different data types to act as values in the key-value pairs.
ShotExample
struct type variable structDecode
is initialized in a similar way; it stores JSON data of the same type.
Free Resources