douhan4812 2017-02-04 19:09
浏览 53
已采纳

如何解码以下JSON?

I have a JSON object of the format

{
  "results": [
    {
      "hits": [
        {
          "title": "Juliette DELAUNAY",
          "author:url": "abc.com"
        }
        ]
    }
    ]
}

To decode in my go program, I have made the following structs

type results struct{
    Result []result `json:"results"`
}

type result struct{
    Hits []hit `json:"hits"`
}

type hit struct{
    Name string `json:"title"`
    Url string `json:"author:url"`
}
var m =make(map[string]string)
var t results

But when I try to do the following,

decoder := json.NewDecoder(resp.Body)


    err = decoder.Decode(&t)
    if err != nil {
        fmt.Println(err)
    }


    for _,x := range t.Result[0].Hits{
        m[x.Name] = x.Url
        fmt.Println(x.Name,x.Url)
    }

It gives a runtime error saying index is out of range. What am I doing wrong? Are my structs incorrect for the given json?

EDIT : The JSON file I need to decode

var jsonStr = []byte(`{"requests":[{"indexName":"recherchepepitesAtoZ","params":"query=x&hitsPerPage=2817&maxValuesPerFacet=42&page=0&facets=%5B%22field_frenchtech_hub_pepite%22%2C%22field_categorie%22%2C%22field_frenchtech_hub_pepite%22%5D&tagFilters="}]}`)
    req, err := http.NewRequest("POST", "http://6y0slgl8yj-dsn.algolia.net/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20vanilla%20JavaScript%20(lite)%203.20.4%3Binstantsearch.js%201.10.4%3BJS%20Helper%202.18.0&x-algolia-application-id=6Y0SLGL8YJ&x-algolia-api-key=6832a361e1e1628f8ddb2483623104c6", bytes.NewBuffer(jsonStr))
    //req.Header.Set("X-Custom-Header", "application/x-www-form-urlencoded")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
  • 写回答

1条回答 默认 最新

  • doujiao7325 2017-02-04 20:19
    关注

    Here is a slightly modified version that works on my machine and go playground:

    GoPlayground

    package main
    
    import (
      "encoding/json"
      "fmt"
      "strings"
    )
    
    type results struct {
      Result []result `json:"results"`
    }
    
    type result struct {
      Hits []hit `json:"hits"`
    }
    
    type hit struct {
      Name string `json:"title"`
      Url  string `json:"author:url"`
    }
    
    var m = make(map[string]string)
    
    func main() {
      jsonSample := `{
      "results": [
        {
          "hits": [
            {
              "title": "Juliette DELAUNAY",
              "author:url": "abc.com"
            }
            ]
        }
        ]
      }`
    
      var t results
      decoder := json.NewDecoder(strings.NewReader(jsonSample))
    
      err := decoder.Decode(&t)
      if err != nil {
        fmt.Println(err)
      }
    
      for _, x := range t.Result[0].Hits {
        m[x.Name] = x.Url
        fmt.Println(x.Name, x.Url)
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?