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 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)