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:
- "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:
- "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
- Field int 'json:"myName"'
- Field int 'json:"myName,omitempty?'
- Field int 'json:"-"'
Go JSON Example 1
- package main
- import "encoding/json"
- import "fmt"
-
- func main() {
- bolType, _ := json.Marshal(false)
- fmt.Println(string(bolType))
- intType, _ := json.Marshal(10)
- fmt.Println(string(intType))
- fltType, _ := json.Marshal(3.14)
- fmt.Println(string(fltType))
- strType, _ := json.Marshal("DotNetTPoint")
- fmt.Println(string(strType))
- slcA := []string{"sun", "moon", "star"}
- slcB, _ := json.Marshal(slcA)
- fmt.Println(string(slcB))
- mapA := map[string]int{"sun": 1, "moon": 2}
- mapB, _ := json.Marshal(mapA)
- fmt.Println(string(mapB))
- }
Output:
false
10
3.14
"DotNetTPoint"
["sun","moon","star"]
{"moon":2,"sun":1}
Go JSON Example 2 (User Defined Data Type)
- package main
-
- import (
- "encoding/json"
- "fmt"
- "os"
- )
-
- type Response1 struct {
- Position int
- Planet []string
- }
- type Response2 struct {
- Position int 'json:"position"'
- Planet []string 'json:"planet"'
- }
-
- func main() {
- res1A := &Response1{
- Position: 1,
- Planet: []string{"mercury", "venus", "earth"}}
- res1B, _ := json.Marshal(res1A)
- fmt.Println(string(res1B))
-
- res2D := &Response2{
- Position: 1,
- Planet: []string{"mercury", "venus", "earth"}}
- res2B, _ := json.Marshal(res2D)
- fmt.Println(string(res2B))
-
-
- byt := []byte('{"pi":6.13,"place":["New York","New Delhi"]}`)
- var dat map[string]interface{}
- if err := json.Unmarshal(byt, &dat); err != nil {
- panic(err)
- }
- fmt.Println(dat)
- num := dat["pi"].(float64)
- fmt.Println(num)
- strs := dat["place"].([]interface{})
- str1 := strs[0].(string)
- fmt.Println(str1)
-
-
- str := `{"Position": 1, "Planet": ["mercury", "venus"]}`
- res := Response2{}
- json.Unmarshal([]byte(str), &res)
- fmt.Println(res)
- fmt.Println(res.Planet[1])
- enc := json.NewEncoder(os.Stdout)
- d := map[string]string{"1":"mercury" , "2": "venus"}
- enc.Encode(d)
-
- }
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