json - Golang 解码 json 映射和数组

标签 json go

看完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 )

问题:

  1. 如果 json 是一个数组,我想遍历每个并打印电子邮件。
  2. 如果json是map,我想直接打印email

播放:http://play.golang.org/p/UPoFxorqWl

最佳答案

根据我的经验,使用 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/

相关文章:

javascript - 在客户端/服务器通信中使用这两种不同的风格有什么优缺点吗?

android - 另一个 AsyncTask 问题 - 内部类看不到 doInBackground 方法

c++ - 如何使用 nlohmann::json 将 json 对象转换为 map ?

go - 如何检测 Golang 中打开文件的文件名更改

go - 无效的接收器类型-可以与myType结构一起使用吗?

c# - 从 XML 填充对象

pointers - golang指针之间的区别

json - 使用 "embedded"键将 JSON 解码为结构

go - 如何从用作泛型的接口(interface)访问结构属性

java - org.json 与 Maven 的依赖关系给出 NoClassDefFoundError