Golang json demo code.

To parse of stringify a json, easily use encoding/json module.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
type JsonStruct struct {
    Foo int      `json:"foo"`
    Bar []string `json:"bar"`
}

slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.Marshal(slcD)
fmt.Println(string(slcB))

mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB))

jsonStruct := &JsonStruct{
    Foo:   1,
    Bar: []string{"google", "apple", "microsoft"}}
jsonByte, _ := json.Marshal(jsonStruct)
fmt.Println(jsonByte)
fmt.Println(string(jsonByte))

var jsonString = `
    {
        "foo": 1,
        "bar": ["google", "apple", "microsoft"]
    }
`
var newJsonStruct JsonStruct
err := json.Unmarshal([]byte(jsonString), &newJsonStruct)
if err != nil {
    log.Fatalln(err)
}
fmt.Println(newJsonStruct)