json - Go Lang 帮助 - 访问数组/接口(interface) slice

标签 json dictionary go interface

我正在尝试使用嵌套数据在 GO 中解码动态/随机 JSON 响应

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

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

正文是来自 HTTP 服务器的 JSON 结果,我对其进行解码,结果看起来是一段字节。

主体:[]uint8

正文:{“结果”:[{“代码”:500.0,“错误”:[“配置文件'c2-web-2.conf'已经存在。”],“状态”:“对象不能创建。”}]}

所以我将它解码为 resp 并且按预期工作。

RESP:映射[字符串]接口(interface){}

RESP: map [结果:[ map [代码:%!s(float64=500) 错误:[配置文件“c2-web-2.conf”已经存在。]状态:无法创建对象。]] ]<

我能够访问包含关键结果的 map 。

RESP[结果]:[]接口(interface){}

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

现在我想访问它的是 resp["results"] 中的“代码”、“错误”和“状态”这看起来像一个数组或 slice ,我已经尝试对其进行索引但我得到了错误在编译时

./create_host.go:62: invalid operation: resp["results"][0] (type interface {} 不支持索引)

我做了很多谷歌搜索,尝试在 resp["results"] 等中解码数据,但几天后我没有取得太大进展。

我应该如何访问似乎是数组成员的 map ?无法保证数据结构,因此我无法创建结构并将其解码。

谢谢

最佳答案

一位同事提供了下面的代码片段,可以访问我正在寻找的 map 条目。

    respBody, _ := ioutil.ReadAll(response.Body)

    var rsp interface{}
    if err := json.Unmarshal(respBody, &rsp); err != nil {
            log.Fatal(err)
    }
    resultMap := rsp.(map[string]interface{})["results"].([]interface{})[0].(map[string]interface{})
    fmt.Printf("test: %s<\n", resultMap["errors"] )

测试:[配置文件'c2-web-2.conf'已经存在。]<

关于json - Go Lang 帮助 - 访问数组/接口(interface) slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780558/

相关文章:

go - 函数结束后,golang没有释放变量

go - 我如何在 func 中声明一片 chan( channel )

github - 解析 access_token 的 Github 响应

arrays - 在单个 JSON Patch 操作中向数组添加多个值?

java - 使用Gson将json字符串解析为对象

Python - 使用元组比较字典列表 - 意外行为?

generics - 如何将 Dictionary<string, object> 的键转换为已排序的 string[]

java - 如何使用 Gson、Retrofit、Active Android 将嵌套 JSON 对象反序列化为字符串

c# - 无法将 HttpResponseMessage 反序列化为模型对象

ios - 如何从Swift 4/json字典中的多值键检索单个值?