-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (51 loc) · 1.24 KB
/
main.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"encoding/json"
"fmt"
)
func main() {
fmt.Println("Consuming json")
userJson := []byte(`
{
"id":1,
"name":"John Doe",
"email":"[email protected]",
"password":"ItsASecret",
"accounts":[
{
"id":1,
"name":"Google",
"email":"[email protected]",
"password":"AccountPassword",
"accounts":null
}
]
}
`)
fmt.Println("User is a valid json:", json.Valid(userJson))
DecodeJson(userJson)
}
func DecodeJson(userJson []byte) {
// var user User
// err := json.Unmarshal(userJson, &user) // converting json into a struct
var kvPairs map[string]interface{}
err := json.Unmarshal(userJson, &kvPairs) // converting json into kv pairs
if err != nil {
panic(err)
}
// fmt.Printf("%#v\n", kvPairs)
// fmt.Printf("%+v\n", user)
LoopOverMap(kvPairs)
}
func LoopOverMap(mapData map[string]interface{}) {
for k, v := range mapData {
fmt.Printf("The key is %s and the value is %v and type is %T\n", k, v, v)
}
}
type User struct {
Id int `json:"id"` // aliasing json
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"-"` // removing fields from json output
Accounts []User `json:"accounts,omitempty"` // omiting nil values
}