如何解码以下 JSON 数据?

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

How do I decode the following JSON?

问题

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

  1. {
  2. "results": [
  3. {
  4. "hits": [
  5. {
  6. "title": "Juliette DELAUNAY",
  7. "author:url": "abc.com"
  8. }
  9. ]
  10. }
  11. ]
  12. }

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

  1. type results struct {
  2. Result []result `json:"results"`
  3. }
  4. type result struct {
  5. Hits []hit `json:"hits"`
  6. }
  7. type hit struct {
  8. Name string `json:"title"`
  9. Url string `json:"author:url"`
  10. }
  11. var m = make(map[string]string)
  12. var t results

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

  1. decoder := json.NewDecoder(resp.Body)
  2. err = decoder.Decode(&t)
  3. if err != nil {
  4. fmt.Println(err)
  5. }
  6. for _, x := range t.Result[0].Hits {
  7. m[x.Name] = x.Url
  8. fmt.Println(x.Name, x.Url)
  9. }

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

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

  1. 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="}]}`)
  2. 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))
  3. req.Header.Set("Content-Type", "application/json")
  4. client := &http.Client{}
  5. resp, err := client.Do(req)
  6. if err != nil {
  7. panic(err)
  8. }
  9. defer resp.Body.Close()

请问我做错了什么?

英文:

I have a JSON object of the format

  1. {
  2. "results": [
  3. {
  4. "hits": [
  5. {
  6. "title": "Juliette DELAUNAY",
  7. "author:url": "abc.com"
  8. }
  9. ]
  10. }
  11. ]
  12. }

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

  1. type results struct{
  2. Result []result `json:"results"`
  3. }
  4. type result struct{
  5. Hits []hit `json:"hits"`
  6. }
  7. type hit struct{
  8. Name string `json:"title"`
  9. Url string `json:"author:url"`
  10. }
  11. var m =make(map[string]string)
  12. var t results

But when I try to do the following,

  1. decoder := json.NewDecoder(resp.Body)
  2. err = decoder.Decode(&t)
  3. if err != nil {
  4. fmt.Println(err)
  5. }
  6. for _,x := range t.Result[0].Hits{
  7. m[x.Name] = x.Url
  8. fmt.Println(x.Name,x.Url)
  9. }

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

  1. 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="}]}`)
  2. 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))
  3. //req.Header.Set("X-Custom-Header", "application/x-www-form-urlencoded")
  4. req.Header.Set("Content-Type", "application/json")
  5. client := &http.Client{}
  6. resp, err := client.Do(req)
  7. if err != nil {
  8. panic(err)
  9. }
  10. defer resp.Body.Close()

答案1

得分: 0

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

Go Playground

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. )
  7. type results struct {
  8. Result []result `json:"results"`
  9. }
  10. type result struct {
  11. Hits []hit `json:"hits"`
  12. }
  13. type hit struct {
  14. Name string `json:"title"`
  15. Url string `json:"author:url"`
  16. }
  17. var m = make(map[string]string)
  18. func main() {
  19. jsonSample := `{
  20. "results": [
  21. {
  22. "hits": [
  23. {
  24. "title": "Juliette DELAUNAY",
  25. "author:url": "abc.com"
  26. }
  27. ]
  28. }
  29. ]
  30. }`
  31. var t results
  32. decoder := json.NewDecoder(strings.NewReader(jsonSample))
  33. err := decoder.Decode(&t)
  34. if err != nil {
  35. fmt.Println(err)
  36. }
  37. for _, x := range t.Result[0].Hits {
  38. m[x.Name] = x.Url
  39. fmt.Println(x.Name, x.Url)
  40. }
  41. }

请注意,这是一个用于解析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

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. )
  7. type results struct {
  8. Result []result `json:"results"`
  9. }
  10. type result struct {
  11. Hits []hit `json:"hits"`
  12. }
  13. type hit struct {
  14. Name string `json:"title"`
  15. Url string `json:"author:url"`
  16. }
  17. var m = make(map[string]string)
  18. func main() {
  19. jsonSample := `{
  20. "results": [
  21. {
  22. "hits": [
  23. {
  24. "title": "Juliette DELAUNAY",
  25. "author:url": "abc.com"
  26. }
  27. ]
  28. }
  29. ]
  30. }`
  31. var t results
  32. decoder := json.NewDecoder(strings.NewReader(jsonSample))
  33. err := decoder.Decode(&t)
  34. if err != nil {
  35. fmt.Println(err)
  36. }
  37. for _, x := range t.Result[0].Hits {
  38. m[x.Name] = x.Url
  39. fmt.Println(x.Name, x.Url)
  40. }
  41. }

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:

确定