doupu1727 2019-07-06 08:37
浏览 36
已采纳

解组不带结构的未知JSON字段

I am trying to unmarshal a JSON object which has an optional array, I am doing this without an array and this is what I got so far:

import (
    "encoding/json"
    "fmt"
)

func main() {

    jo := `
        {
            "given_name": "Akshay Raj",
            "name": "Akshay",
            "country": "New Zealand",
            "family_name": "Gollahalli",
            "emails": [
                "name@example.com"
                ]
        }
        `
    var raw map[string]interface{}
    err := json.Unmarshal([]byte(jo), &raw)
    if err != nil {
        panic(err)
    }

    fmt.Println(raw["emails"][0])

}

The emails field might or might not come sometime. I know I can use struct and unmarshal it twice for with and without array. When I try to get the index 0 of raw["emails"][0] I get the following error

invalid operation: raw["emails"][0] (type interface {} does not support indexing)

Is there a way to get the index of the emails field?

Update 1

I can do something like this fmt.Println(raw["emails"].([]interface{})[0]) and it works. Is this the only way?

  • 写回答

3条回答 默认 最新

  • duanqiu9104 2019-07-06 08:58
    关注

    The easiest way is with a struct. There's no need to unmarshal twice.

    type MyStruct struct {
        // ... other fields
        Emails []string `json:"emails"`
    }
    

    This will work, regardless of whether the JSON input contains the emails field. When it is missing, your resulting struct will just have an uninitialized Emails field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题