From 5cc780f37edc8658ac5a62f516aad46d55a44331 Mon Sep 17 00:00:00 2001 From: Inanc Gumus Date: Thu, 16 May 2019 23:21:35 +0300 Subject: [PATCH] add: advanced decoding example --- 24-structs/08-decoding-2/main.go | 63 +++++++++++++++++++++++++++++ 24-structs/08-decoding-2/users.json | 24 +++++++++++ 2 files changed, 87 insertions(+) create mode 100644 24-structs/08-decoding-2/main.go create mode 100644 24-structs/08-decoding-2/users.json diff --git a/24-structs/08-decoding-2/main.go b/24-structs/08-decoding-2/main.go new file mode 100644 index 0000000..cc8fe49 --- /dev/null +++ b/24-structs/08-decoding-2/main.go @@ -0,0 +1,63 @@ +// For more tutorials: https://blog.learngoprogramming.com +// +// Copyright © 2018 Inanc Gumus +// Learn Go Programming Course +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ +// + +/* This lecture will be added later */ + +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "os" +) + +type user struct { + Name string `json:"username"` + Permissions map[string]bool `json:"perms"` + + Devices []struct { + Name string `json:"name"` + Battery int `json:"battery"` + } `json:"devices"` +} + +// type device struct { +// Name string `json:"name"` +// Battery int `json:"battery"` +// } + +func main() { + var input []byte + for in := bufio.NewScanner(os.Stdin); in.Scan(); { + input = append(input, in.Bytes()...) + } + + var users []user + if err := json.Unmarshal(input, &users); err != nil { + fmt.Println(err) + return + } + + for _, user := range users { + fmt.Print("+ ", user.Name) + + switch p := user.Permissions; { + case p == nil: + fmt.Print(" has no power.") + case p["admin"]: + fmt.Print(" is an admin.") + case p["write"]: + fmt.Print(" can write.") + } + + for _, device := range user.Devices { + fmt.Printf("\n\t[ %-10s: %d%% ]", device.Name, device.Battery) + } + fmt.Println() + } +} diff --git a/24-structs/08-decoding-2/users.json b/24-structs/08-decoding-2/users.json new file mode 100644 index 0000000..14d2d07 --- /dev/null +++ b/24-structs/08-decoding-2/users.json @@ -0,0 +1,24 @@ +[ + { + "username": "inanc", + "devices": [ + { "name": "laptop", "battery": 10 }, + { "name": "phone", "battery": 30 } + ] + }, + { + "username": "god", + "perms": { + "admin": true + }, + "devices": [ + { "name": "omniverse", "battery": 95 } + ] + }, + { + "username": "devil", + "perms": { + "write": true + } + } +]