【问题标题】:GO parse nested json arrayGO解析嵌套的json数组
【发布时间】:2017-09-08 20:40:28
【问题描述】:
{
    "meta": {
       "type": "RESPONSE",
       "application": "",
       "data0": {
         some data
       },
      "lv1": [
      {
        "status": "SUCCESS",
        "response-type": "JSON",
        "message": {},
        "response": {
        "more_data": "TRUE",
        "no_result": "5",
        "current_page": "1",
        "data": [[
         "1",
         "2", 
         "3"]]
        }
      }
     ]
   }
}

type response struct {
    META struct {
        LV []struct {
            RESPONSE struct {
                Data []struct {
                    array []struct {
                        val []string
                    }
                } `json:"data"`
            } `json:"response"`
        } `json:"lv1"`
    } `json:"meta"`

}

如何获取以下值?

"data": [[
         "1",
         "2", 
         "3"]]

我已经尝试过接口和结构。使用接口导致接口类型为[1 2 3],我不确定如何获取这些值。使用 struct 时,我在尝试使用错误消息映射数组数组时遇到了问题:

"无法将数组解组到 Go 结构字段 .data 类型为 struct { vals []字符串}"

【问题讨论】:

  • 您发布的 JSON 在某处无效...

标签: go


【解决方案1】:

它是一个字符串数组的数组,而不是一个包含结构体数组的结构体数组,所以你想要的更像是:

type response struct {
    Meta struct {
        Lv []struct {
            Response struct {
                Data [][]string `json:"data"`
            } `json:"response"`
        } `json:"lv1"`
    } `json:"meta"`
}

(我还更改了全大写字段名称以匹配预期的 Go 代码样式。)

对于它的价值,有一个方便的 JSON-to-Go 工具 here 在删除 some data 位(这使 JSON 无效)之后给了我这个供您输入:

type AutoGenerated struct {
    Meta struct {
        Type        string `json:"type"`
        Application string `json:"application"`
        Data0       struct {
        } `json:"data0"`
        Lv1 []struct {
            Status       string `json:"status"`
            ResponseType string `json:"response-type"`
            Message      struct {
            } `json:"message"`
            Response struct {
                MoreData    string     `json:"more_data"`
                NoResult    string     `json:"no_result"`
                CurrentPage string     `json:"current_page"`
                Data        [][]string `json:"data"`
            } `json:"response"`
        } `json:"lv1"`
    } `json:"meta"`
}

【讨论】:

  • 您链接的工具非常棒,感谢分享。我只需要删除一些重复的定义,否则它会生成一个完美的结构。再次感谢!
  • 同意!这实际上是一个很棒的工具 - 为我节省了很多时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多