donglisi8644 2018-04-10 05:53
浏览 78
已采纳

如何在Golang中不解组嵌套的JSON

I have some JSON that I wish to unmarshal in Go. One of the top-level keys of the JSON dictionary has a value that is also parsable JSON. For example:

{ 
    "Name": "Tony",
    "Age": 50,
    "Extra": {\"Weight\":180}
}

I have a corresponding struct that I want to unmarsal to:

type Person struct {
    Name string
    Age int
    Extra []byte
 }

I want the Extra key to be a byte array because the JSON structure will vary and the structure of it is not important to the program being written. The program simply needs to push this data along down the line as a byte array.

How can I coax the Go JSON encoder to handle the value of extra like this?

  • 写回答

2条回答 默认 最新

  • douzhuan1467 2018-04-10 06:07
    关注

    You have two options:

    Using json.RawMessage

    Here you have to slightly change your struct:

    type Person struct {
        Name string
        Age int
        Extra *json.RawMessage
    }
    

    then, you can Unmarshal as usual

    person := Person{}
    err := json.Unmarshal(raw_bytes, &person)
    // handle err
    

    finally, you can Unmarshal Extra again, you can even do some assertion type on it to previously detect the type

    var extra_option_1 string
    extra_option_2 := AnotherStruct{}
    
    err := json.Unmarshal(raw_bytes, &extra_option_1)
    // handle err
    
    // or
    
    err := json.Unmarshal(raw_bytes, &extra_option_2)
    // handle err
    

     Using map[string]interface{}{} - honestly not so useful in your case

    You can directly unmarshal "unknown" or dynamics payloads using a general map[string]interface{}{}.
    BUT I discourage this usage because is slower and you should always know what to expect.

    Anyway, hereafter is a pseudo code:

    payload := map[string]interface{}{}
    err := json.Unmarshal(raw_bytes, &payload)
    // handle err
    

    In this last case, you need even to do assertion to each field.

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

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题