-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-encode-string.go
47 lines (39 loc) · 1.24 KB
/
json-encode-string.go
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// This sample program demonstrates how to encode a JSON string.
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Create a map of key/value pairs and parses the data into JSON
emp := make(map[string]interface{})
emp["name"] = "Alfie Qashwa"
emp["jobtitle"] = "Software Developer"
emp["phone"] = map[string]interface{}{
"home": "021-749-0xxx",
"office": "0812-8093-1xxx",
}
emp["email"] = "alfieqashwa@gmail.com"
// Unmarshal the map into a JSON string.
empData, err := json.Marshal(emp)
if err != nil {
fmt.Println(err.Error())
return
}
jsonStr := string(empData)
fmt.Println("The JSON data is:")
fmt.Println(jsonStr)
}
/*
=== OUTPUT ===
The JSON data is:
{"email":"alfieqashwa@gmail.com","jobtitle":"Software Developer","name":"Alfie Qashwa","phone":{"home":"021-749-0xxx","office":"0812-8093-1xxx"}}
=== SYNTAX ===
func Marshal(v interfaace{}) ([]byte, error)
=== EXPLANATION ===
Marshal function is good for producing JSON that could be returned in a network response,
like a Restfult API. The function Marshal returns two values:
the encoded JSON data as slice byte and ane error value.
Using Marshal, we can also encode the values of struct type as json values that will help us
to quickly build JSON-based APIs.
*/