如何解码以下 JSON 数据?

huangapple go评论87阅读模式
英文:

How do I decode the following JSON?

问题

我有一个格式为JSON的对象:

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

为了在我的Go程序中解码它,我创建了以下结构体:

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

但是当我尝试执行以下操作时:

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)
}

它会报运行时错误,提示索引超出范围。我做错了什么?我的结构体对给定的JSON是否不正确?

编辑:我需要解码的JSON文件如下:

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("Content-Type", "application/json")

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

请问我做错了什么?

英文:

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

得分: 0

这是一个在我的机器和Go Playground上运行的稍作修改的版本:

Go Playground

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)
  }
}

请注意,这是一个用于解析JSON数据的Go语言示例代码。它定义了一些结构体类型,并使用encoding/json包来解码JSON数据。在main函数中,它将JSON样本解码为results类型的变量t,然后遍历结果并将名称和URL存储在m映射中。最后,它打印出每个名称和URL。

英文:

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)
  }
}

huangapple
  • 本文由 发表于 2017年2月5日 03:09:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/42044448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定