dousi6303 2016-06-13 00:57
浏览 66

Go Lang帮助-访问接口数组/切片

I'm trying to decode dynamic/random JSON responses in GO, with nested data

    body, _ := ioutil.ReadAll(response.Body)
    resp := make(map[string]interface{})
    err = json.Unmarshal(body, &resp)

    fmt.Printf("BODY: %T<
", body)
    fmt.Printf("BODY: %s<
", body)
    fmt.Printf("RESP: %s<
", resp)
    fmt.Printf("RESP: %T<
", resp)
    fmt.Printf("RESP[results]: %T<
", resp["results"])
    fmt.Printf("RESP[results]: %s<
", resp["results"])

body is the JSON result from the HTTP server and I unmarshall it and the result looks to be a slice of bytes.

BODY: []uint8

BODY: {"results":[{"code":500.0,"errors":["Configuration file 'c2-web-2.conf' already exists."],"status":"Object could not be created."}]}

So I unmarshall it into resp and that works as expected.

RESP: map[string]interface {}

RESP: map[results:[map[code:%!s(float64=500) errors:[Configuration file 'c2-web-2.conf' already exists.] status:Object could not be created.]]]<

I'm able to access the map with the key results.

RESP[results]: []interface {}

RESP[results]: [map[code:%!s(float64=500) errors:[Configuration file 'conf.d/hosts/c2-web-2.conf' already exists.] status:Object could not be created.]]<

Now what i want to access it the "code", "errors" and "status" which is in resp["results"] This looks like an array or slice and I've tried indexing it but I get the error at compile time

./create_host.go:62: invalid operation: resp["results"][0] (type interface {} does not support indexing)

I've done a lot of googling, tried unmarshalling the data within resp["results"] etc, but after a few days I have not made much progress.

How should I access the map which seems to be a member of an array? The data structure is not guaranteed so I can't create a structure and unmarshall into that.

Thanks

  • 写回答

2条回答 默认 最新

  • dqnhfbc3738 2016-06-13 01:14
    关注

    I believe you need to do a type assertion. You have an interface{}, but you need some sort of slice to index into. Try resp["results"].([]interface{})[0]? (Sorry, haven't had a chance to test this myself.)

    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记