Saturday 4 September 2021

Go JSON

 Go has built-in support for JSON encoding and decoding. it also supports custom datatypes.

The Marshal function is used to convert go data types into JSON format.

Marshal function syntax is:

  1. "func Marshal(v interface{}) ([]byte, error)"  

Marshal returns the JSON encoding of v.

Boolean is converted to JSON booleans. Floating point, integer, and Number are converted to JSON numbers. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler.

The decoding of JSON is done using Unmarshal function.

Unmarshal function syntax is:

  1. "func Unmarshal(data []byte, v interface{}) error"  

Unmarshal decodes JSON-encoded value and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

We can also customize the fields stored under the "json" key in the struct field's tag. we can have name of the field, followed by a comma-separated list of options. Like

  1. Field int 'json:"myName"' // The appears in JSON as key "myName".  
  2. Field int 'json:"myName,omitempty?'// The field is omitted from the object if its value is empty,  
  3. Field int 'json:"-"' //// Field is ignored by this package.  

Go JSON Example 1

  1. package main  
  2. import "encoding/json"  
  3. import "fmt"  
  4.   
  5. func main() {  
  6.     bolType, _ := json.Marshal(false//boolean Value  
  7.     fmt.Println(string(bolType))  
  8.     intType, _ := json.Marshal(10// integer value  
  9.     fmt.Println(string(intType))  
  10.     fltType, _ := json.Marshal(3.14//float value  
  11.     fmt.Println(string(fltType))  
  12.     strType, _ := json.Marshal("DotNetTPoint"// string value  
  13.     fmt.Println(string(strType))  
  14.     slcA := []string{"sun""moon""star"//slice value  
  15.     slcB, _ := json.Marshal(slcA)  
  16.     fmt.Println(string(slcB))  
  17.     mapA := map[string]int{"sun"1"moon"2//map value  
  18.     mapB, _ := json.Marshal(mapA)  
  19.     fmt.Println(string(mapB))  
  20. }  

Output:

false
10
3.14
"DotNetTPoint"
["sun","moon","star"]
{"moon":2,"sun":1}

Go JSON Example 2 (User Defined Data Type)

  1. package main  
  2.   
  3. import (  
  4.     "encoding/json"  
  5.     "fmt"  
  6.     "os"  
  7. )  
  8.   
  9. type Response1 struct {  
  10.     Position   int  
  11.     Planet []string  
  12. }  
  13. type Response2 struct {  
  14.     Position   int      'json:"position"'  
  15.     Planet []string 'json:"planet"'  
  16. }  
  17.   
  18. func main()  {  
  19.     res1A := &Response1{  
  20.         Position:   1,  
  21.         Planet: []string{"mercury""venus""earth"}}  
  22.     res1B, _ := json.Marshal(res1A)  
  23.     fmt.Println(string(res1B))  
  24.   
  25.     res2D := &Response2{  
  26.         Position:   1,  
  27.         Planet: []string{"mercury""venus""earth"}}  
  28.     res2B, _ := json.Marshal(res2D)  
  29.     fmt.Println(string(res2B))  
  30.   
  31.   
  32.     byt := []byte('{"pi":6.13,"place":["New York","New Delhi"]}`)  
  33.     var dat map[string]interface{}  
  34.     if err := json.Unmarshal(byt, &dat); err != nil {  
  35.         panic(err)  
  36.     }  
  37.     fmt.Println(dat)  
  38.     num := dat["pi"].(float64)  
  39.     fmt.Println(num)  
  40.     strs := dat["place"].([]interface{})  
  41.     str1 := strs[0].(string)  
  42.     fmt.Println(str1)  
  43.       
  44.       
  45.     str := `{"Position"1"Planet": ["mercury""venus"]}`  
  46.     res := Response2{}  
  47.     json.Unmarshal([]byte(str), &res)  
  48.     fmt.Println(res)  
  49.     fmt.Println(res.Planet[1])  
  50.     enc := json.NewEncoder(os.Stdout)  
  51.     d := map[string]string{"1":"mercury" , "2""venus"}  
  52.     enc.Encode(d)  
  53.   
  54. }  

Output:

{"Position":1,"Planet":["mercury","venus","earth"]}
{"position":1,"planet":["mercury","venus","earth"]}
map[pi:6.13 place:[New York New Delhi]]
6.13
New York
{1 [mercury venus]}
venus
{"1":"mercury","2":"venus"}

No comments:

Post a Comment