Add a function to walk the JSON

This commit is contained in:
Huy-Ngo 2020-10-28 23:09:29 +07:00
parent 203f415c31
commit 4e5d6c7c76
1 changed files with 26 additions and 16 deletions

42
main.go
View File

@ -9,7 +9,7 @@ import (
"os"
)
type Entry struct {
type Usage struct {
PartOfSpeech string `json:"partOfSpeech"`
Language string `json::"language"`
Definitions []Definition `json:"definitions"`
@ -20,6 +20,30 @@ type Definition struct {
examples []string `json:"examples"`
}
func PrintJSON(json map[string]interface{}) {
for key, value := range json {
switch typ := value.(type) {
case []interface{}:
fmt.Println("Language:", key)
for _, u := range typ {
fmt.Println("{")
switch v := u.(type) {
case map[string]interface{}:
fmt.Println(v["partOfSpeech"])
fmt.Println(v["language"])
fmt.Println(v["definitions"])
default:
fmt.Println("Some other type", v)
}
fmt.Println("},")
}
fmt.Println("]\n")
default:
fmt.Println(key, "is some other type", typ)
}
}
}
func main() {
response, err := http.Get("https://en.wiktionary.org/api/rest_v1/page/definition/général")
@ -40,19 +64,5 @@ func main() {
entries := result.(map[string]interface{})
for key, value := range entries {
switch typ := value.(type) {
case string:
fmt.Println(key, "is string", typ)
case int:
fmt.Println(key, "is int", typ)
case []interface{}:
fmt.Println(key, "is an array:")
for i, u := range typ {
fmt.Println(i, u)
}
default:
fmt.Println(key, "is some other type")
}
}
PrintJSON(entries)
}