看完JSON and Go ,我确实了解在 Go 中解码 json 的基础知识。但是,存在这个问题,输入的 json 有时可以是 map ,有时可以是 map 数组。
考虑以下问题:
package main
import (
"encoding/json"
"fmt"
)
func main() {
b := []byte(`[{"email":"example@test.com"}]`)
c := []byte(`{"email":"example@test.com"}`)
var m interface{}
json.Unmarshal(b, &m)
switch v := m.(type) {
case []interface{}:
fmt.Println("this is b", v)
default:
fmt.Println("No type found")
}
json.Unmarshal(c, &m)
switch v := m.(type) {
case map[string]interface{}:
fmt.Println("this is c", v)
default:
fmt.Println("No type found")
}
}
现在,我如何获得值 email
:example@test.com
在这两种情况下(b
& c
)
问题:
- 如果 json 是一个数组,我想遍历每个并打印电子邮件。
- 如果json是map,我想直接打印email
最佳答案
根据我的经验,使用 interface{} 来处理 json 解码可能会导致一些奇怪的问题,我倾向于避免它。尽管有一些方法可以使用 reflect 包来实现它。
这是基于您的原始解决方案的问题解决方案,希望对您有所帮助。
package main
import (
"encoding/json"
"fmt"
)
type Item struct {
Email string `json:email`
}
func main() {
b := []byte(`[{"email":"example_in_array@test.com"}]`)
//b := []byte(`{"email":"example@test.com"}`)
var m = &Item{}
var ms = []*Item{}
err := json.Unmarshal(b, &m)
if err != nil {
err = json.Unmarshal(b, &ms)
if err != nil {
panic(err)
}
for _, m := range ms {
fmt.Println(m.Email)
}
} else {
fmt.Println(m.Email)
}
}
关于json - Golang 解码 json 映射和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35691811/