在 Golang 中解析 JSON,使用不带键的数组回答

  • 本文关键字:数组 Golang JSON json go
  • 更新时间 :
  • 英文 :


如何处理 json 如果响应附带一个数据数组(在 JS 中是通过获取索引上的必要数据来决定的(,我看到我通过 Unmarshal 将其写入结构中,但我无法将数组保存在结构中,以便我可以从键中获取索引,因为没有可以在其上创建结构的键。

package main
import (
    "fmt"
    "net/http"
)
func main() {
    url := "My request"
    request := "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + url + "&limit=5&origin=*&format=json"
    response, err := http.Get(request)
    if err != nil {
        fmt.Printf("%s", err)
    }
}

这是答案

["bee",["Bee","Beer","Bee Gees","Beef","Beetle"],["Bees are flying insects closely related to wasps and ants, known for their role in pollination and, in the case of the best-known bee species, the European honey bee, for producing honey and beeswax.","Beer is one of the oldest and most widely consumed alcoholic drinks in the world, and the third most popular drink overall after water and tea.","The Bee Gees were a pop music group formed in 1958. Their lineup consisted of brothers Barry, Robin, and Maurice Gibb.","Beef is the culinary name for meat from cattle, particularly skeletal muscle. Humans have been eating beef since prehistoric times.","Beetles are a group of insects that form the order Coleoptera, in the superorder Endopterygota. Their front pair of wings is hardened into wing-cases, elytra, distinguishing them from most other insects."],["https://en.wikipedia.org/wiki/Bee","https://en.wikipedia.org/wiki/Beer","https://en.wikipedia.org/wiki/Bee_Gees","https://en.wikipedia.org/wiki/Beef","https://en.wikipedia.org/wiki/Beetle"]]

您可以定义一个自定义类型,该类型通过将解析的数组值映射到结构中来实现json.Unmarshaler,如下所示:

type SearchResults struct {
  Query   string
  Results []Result
}
type Result struct {
  Name, Description, URL string
}
func (sr *SearchResults) UnmarshalJSON(bs []byte) error {
  array := []interface{}{}
  err := json.Unmarshal(bs, &array)
  if err != nil {
    return err
  }
  sr.Query = array[0].(string)
  for i := range array[1].([]interface{}) {
    sr.Results = append(sr.Results, Result{
      array[1].([]interface{})[i].(string),
      array[2].([]interface{})[i].(string),
      array[3].([]interface{})[i].(string),
    })
  }
  return nil
}
func main() {
  sr := &SearchResults{}
  err := json.Unmarshal([]byte(jsonstr), sr)
  if err != nil {
    panic(err)
  }
  fmt.Printf("OK: query=%qn", sr.Query)
  for i, result := range sr.Results {
    fmt.Printf("OK: result[%d]=%#vn", i, result)
  }
}
// OK: query="bee"
// OK: result[0]=main.Result{Name:"Bee", Description:"Bees are flying insects closely related to wasps and ants, known for their role in pollination and, in the case of the best-known bee species, the European honey bee, for producing honey and beeswax.", URL:"https://en.wikipedia.org/wiki/Bee"}
// OK: result[1]=main.Result{Name:"Beer", Description:"Beer is one of the oldest and most widely consumed alcoholic drinks in the world, and the third most popular drink overall after water and tea.", URL:"https://en.wikipedia.org/wiki/Beer"}
// OK: result[2]=main.Result{Name:"Bee Gees", Description:"The Bee Gees were a pop music group formed in 1958. Their lineup consisted of brothers Barry, Robin, and Maurice Gibb.", URL:"https://en.wikipedia.org/wiki/Bee_Gees"}
// OK: result[3]=main.Result{Name:"Beef", Description:"Beef is the culinary name for meat from cattle, particularly skeletal muscle. Humans have been eating beef since prehistoric times.", URL:"https://en.wikipedia.org/wiki/Beef"}
// OK: result[4]=main.Result{Name:"Beetle", Description:"Beetles are a group of insects that form the order Coleoptera, in the superorder Endopterygota. Their front pair of wings is hardened into wing-cases, elytra, distinguishing them from most other insects.", URL:"https://en.wikipedia.org/wiki/Beetle"}

感谢@Peter的答案和代码示例:https://play.golang.org/p/t-iuGVaRsNM

package main
import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)
func main() {
    //Ask user to enter search parameter
    fmt.Printf("Search something: ")
    var s string
    fmt.Scanf("%s", &s)
    //Create search url
    url := s
    request := "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + url + "&limit=5&origin=*&format=json"
    //Sending request
    response, err := http.Get(request)
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()
    //Unmarshal and store to responsedata interface    
    var responsedata []interface{}
    if err := json.NewDecoder(response.Body).Decode(&responsedata); err != nil {
        log.Fatal(err)
    }
    //Loop through the responsedata and output
    for _, x := range responsedata {
        switch value := x.(type) {
        case string:
            fmt.Println(value)
        case []interface{}:
            for _, v := range value {
                fmt.Println(v.(string))
            }
        }
    }
}

最新更新