首页 > 解决方案 > 在 Go 中解组复杂的 json

问题描述

所以我试图通过 ping 和端点来获取应用程序的分析。我发出了成功的 GET 请求(那里没有错误),但我无法解码 JSON

我需要将以下 json 解码为结构

{
  "noResultSearches": {
    "results": [
      {
        "count": 1,
        "key": "\"note 9\""
      },
      {
        "count": 1,
        "key": "nokia"
      }
    ]
  },
  "popularSearches": {
    "results": [
      {
        "count": 4,
        "key": "6"
      },
      {
        "count": 2,
        "key": "\"note 9\""
      },
      {
        "count": 1,
        "key": "nokia"
      }
    ]
  },
  "searchVolume": {
    "results": [
      {
        "count": 7,
        "key": 1537401600000,
        "key_as_string": "2018/09/20 00:00:00"
      }
    ]
  }
}

我正在使用以下结构

type analyticsResults struct {
    Count int    `json:"count"`
    Key   string `json:"key"`
}

type analyticsVolumeResults struct {
    Count     int    `json:"count"`
    Key       int64 `json:"key"`
    DateAsStr string `json:"key_as_string"`
}

type analyticsPopularSearches struct {
    Results []analyticsResults `json:"results"`
}

type analyticsNoResultSearches struct {
    Results []analyticsResults `json:"results"`
}

type analyticsSearchVolume struct {
    Results []analyticsVolumeResults `json:"results"`
}

type overviewAnalyticsBody struct {
    NoResultSearches analyticsNoResultSearches `json:"noResultSearches"`
    PopularSearches  analyticsPopularSearches  `json:"popularSearches"`
    SearchVolume     analyticsSearchVolume     `json:"searchVolume"`
}

我向端点发出 GET 请求,然后使用响应正文解码 json,但出现错误。以下是保留在我的ShowAnalytics函数中的部分代码

func ShowAppAnalytics(app string) error {
  spinner.StartText("Fetching app analytics")
  defer spinner.Stop()

  fmt.Println()
  req, err := http.NewRequest("GET", "<some-endpoint>", nil)
  if err != nil {
      return err
  }
  resp, err := session.SendRequest(req)
  if err != nil {
      return err
  }
  spinner.Stop()

  var res overviewAnalyticsBody
  dec := json.NewDecoder(resp.Body)
  err = dec.Decode(&res)
  if err != nil {
      return err
  }

  fmt.Println(res)

  return nil
}

json:无法将数组解组为 app.analyticsNoResultSearches 类型的 Go 结构字段 overviewAnalyticsBody.noResultSearches

我在这里做错了什么?为什么我会收到此错误?

标签: jsongo

解决方案


编辑:编辑后,您当前的代码按原样工作。在这里查看:去游乐场

原始答案如下。


您发布的代码与您收到的错误之间存在一些不一致。

我在 Go Playground 上试过(这里是你的版本),我收到以下错误:

json:无法将数字解组为字符串类型的 Go 结构字段 analyticsVolumeResults.key

我们收到此错误是因为 JSONsearchVolume.results.key中是一个数字:

    "key": 1537401600000,

string在 Go 模型中使用了:

Key       string `json:"key"`

如果我们将其更改为int64

Key       int64 `json:"key"`

它可以工作并打印(在Go Playground上尝试):

{{[{1 "note 9"} {1 nokia}]} {[{4 6} {2 "note 9"} {1 nokia}]} {[{7 1537401600000 2018/09/20 00:00:00 }]}}

如果该键有时可能是数字,有时是string,您也可以json.Number在 Go 模型中使用:

Key       json.Number `json:"key"`

推荐阅读