duanfang7270 2018-12-18 23:22
浏览 27
已采纳

捕获嵌套接口值

I'm trying to get the values of a json that was obtained by means of a request.

But I'm not getting the value foo1, I've tried everything but I can not get the value.

The invalid operation error appears.

Can you help me?

{
    "result": {
        "foo1": 1751,
        "foo2": "2018-12-17T00:00:00-02:00",
    }
}

url := "mysite"
req, _ := http.NewRequest("GET", url, nil)
res, _ := http.DefaultClient.Do(req)

defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)

byt := []byte(string(body))

var dat map[string]interface{}

if err := json.Unmarshal(byt, &dat); err != nil {
    panic(err)
}

fmt.Println(dat) //map[result:map[foo1:1751 foo2:2018-12-17T00:00:00-02:00]]
fmt.Println(dat["result"]) //map[foo1:1751 foo2:2018-12-17T00:00:00-02:00]]
foo1  := dat["result"]["foo1"] //invalid operation: dat["result"]["foo1"] (type interface {} does not support indexing)
fmt.Println(foo1)
  • 写回答

1条回答 默认 最新

  • duancai9010 2018-12-19 08:12
    关注

    Elaborating on @zerkms's comment, you need to type assert it to map[string]interface{}. Go playground link

    P.S: Performing a nil check before assigning is always a good idea.

    if exists := dat["result"]; exists != nil { foo1 := dat["result"].(map[string]interface{}) }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号