dousenjue3214 2014-05-10 04:47
浏览 32

如何访问json解码上的接口字段?

I have a json document and I'm using a client which decodes the document in an interface (instead of struct) as below:

var jsonR interface{}
err = json.Unmarshal(res, &jsonR)

How can I access the interface fields? I've read the go doc and blog but my head still can't get it. Their example seem to show only that you can decode the json in an interface but doesn't explain how its fields can be used.

I've tried to use a range loop but it seems the story ends when I reach a map[string]interface. The fields that I need seem to be in the interface.

for k, v := range jsonR {
    if k == "topfield" {
        fmt.Printf("k  is %v, v is %v", k, v)

    }

}
  • 写回答

2条回答 默认 最新

  • duankong8998 2014-05-10 05:04
    关注

    The value inside the interface depends on the json structure you're parsing. If you have a json dictionary, the dynamic type of jsonR will be: map[string]interface{}.

    Here's an example.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
    )
    
    func main() {
        a := []byte(`{"topfield": 123}`)
        var v interface{}
        if err := json.Unmarshal(a, &v); err != nil {
            log.Fatalf("unmarshal failed: %s", err)
        }
        fmt.Printf("value is %v", v.(map[string]interface{})["topfield"])
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题