登录
首页 >  Golang >  Go问答

解析JSON后无法访问Golang中的对象数组

来源:stackoverflow

时间:2024-03-25 11:24:36 225浏览 收藏

在 Go 中解析 JSON 后无法访问对象数组的问题可能是由于 JSON 数据结构中嵌套的键导致的。原始 JSON 数据中,“parameters”键嵌套在“_class”键的 map 中,而不是直接位于 actions 数组中的对象中。因此,使用 actionzero.(map[string]interface{})["parameters"] 无法正确访问该数组。

问题内容

向服务器发出请求后 - 我得到如下 json:

{
  "actions": [
    {
      "class": "...",
      "parameters": [
        { ... }
        { ... }
       ]
    }
  ]
  ...
}

我放入此数据的变量类型是 map[string]interface{}

我想访问 actions 数组的第一个对象中的 parameters 数组。我可以成功获取 class 属性 - data.(map[string]interface{})["class"]

但是,如果我对 parameters 属性尝试相同的操作 - 我会得到 nil ...

我尝试了 data.(map[string][]interface{})["parameters"] - 但出现错误 panic: 接口转换:接口 {} 是 map[string]interface {},而不是 map[string ][]接口 {}

知道我在这里缺少什么吗?

编辑:

golang 代码是这样的:

func main() {

    var jsonresult map[string]interface{}

    errorfromjsonfetching := utils.getjson(theurl, &jsonresult)
    if errorfromjsonfetching != nil {
      fmt.printf("error from checking deploy build: %#v\n", errorfromjsonfetching)
    }

    // get the top level "actions" prop ..
    actionzero := jsonresult["actions"].([]interface{})[0]

    fmt.printf("class prop: /%v %t\n", actionzero.(map[string]interface{})["class"], actionzero)
    fmt.printf("parameters prop: /%v %t\n", actionzero.(map[string]interface{})["parameters"], actionzero)

}

getjson 函数来自项目中的另一个文件:

func getjson (url string, result interface{}) error {

  fmt.printf("getting json from %v\n", url)

  resp, err := http.get(url)

  if err != nil {
    return fmt.errorf("cannot fetch url %q: %v\n", url, err)
  }

  defer resp.body.close()

  if resp.statuscode != http.statusok {
    return fmt.errorf("bad resposne status code: %s\n", resp.status)
  }

  // attempt to put the json in the `result` ..
  err = json.newdecoder(resp.body).decode(&result)

  if err != nil {
    return fmt.errorf("could not decode the json from response, err: %v\n", err)
  }

  return nil;
}

编辑2:

感谢评论中 @larsks 的想法 - 我直接在 main.go 文件中使用字符串中的 json 创建了一个最小的代码示例 - 并且一切正常。

然后我再次访问浏览器并尝试再次获取数据 - 直接点击 url 或使用页面中的 $.getjson - 并且都返回一个相同的 json 数据。

但是,在我的 go 代码中,当我转储 json 数据时 - 我看到 actions 的第一个成员:

map[_class:hudson.model.ParametersDefinitionProperty parameterDefinitions:[map[...

因此,当我尝试通过键 parameterdefinitions 获取 parameters 数组时 - 然后我得到对象数组...:o

sooooo ...我不知道发生了什么...要么 go 本身在从后端获取 json 数据时修改 json 数据,要么后端本身返回不同的内容,具体取决于数据的获取方式。

(顺便说一句,后端是 jenkins api ...所以我不知道为什么我在 go 中得到 parameterdefinitions 而不是 parameters ... :( ...)


正确答案


感谢您更新您的问题;拥有正确的数据可以更轻松地回答。

如果您在问题中包含的代码是我们可以获取并运行的代码,那就最好了——这意味着它可以编译并运行,并且当在您的问题中给出示例数据时,它会产生您所询问的行为。

我修改了您的代码,以便可以在本地运行它,主要是将 getjson 方法替换为从名为 data.json 的文件中读取的内容,而不是使用 api:

package main

import (
  "encoding/json"
  "fmt"
  "os"
)

func getjson(result interface{}) error {
  datafile, err := os.open("data.json")
  if err != nil {
    panic(err)
  }

  return json.newdecoder(datafile).decode(&result)
}

func main() {
  var jsonresult map[string]interface{}

  errorfromjsonfetching := getjson(&jsonresult)
  if errorfromjsonfetching != nil {
    fmt.printf("error from checking deploy build: %#v\n", errorfromjsonfetching)
  }

  // get the top level "actions" prop ..
  actionzero := jsonresult["actions"].([]interface{})[0]

  fmt.printf("class prop: /%v %t\n", actionzero.(map[string]interface{})["class"], actionzero)
  fmt.printf("parameters prop: /%v %t\n", actionzero.(map[string]interface{})["parameters"], actionzero)
}

如果我向它提供这个示例数据,我相信它与您在问题中显示的结构相匹配:

{
  "actions": [
    {
      "class": "name of class",
      "parameters": [
        {
          "name": "alice",
          "color": "blue"
        },
        {
          "name": "bob",
          "count": 10,
        },
        {
          "name": "mallory",
          "valid": false,
        }
      ]
    }
  ]
}

它产生以下输出:

Class prop: /Name of class map[string]interface {}
Parameters prop: /[map[color:blue name:alice] map[count:10 name:bob] map[name:mallory valid:false]] map[string]interface {}

这不会为 parameters 键生成 nil 值。为了更全面地回答您的问题,您能否更新它,以便它具有重现您所询问的行为的示例数据和代码?

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《解析JSON后无法访问Golang中的对象数组》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>