GO解析嵌套的json数组

时间:2017-09-08 20:40:28

标签: go

{
    "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时,我在尝试使用错误消息映射数组数组时遇到了问题:

  

“无法将数组解组为类型为struct {的Go struct field .data   vals [] string}“

1 个答案:

答案 0 :(得分:5)

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

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"`
}