我需要使用此URL https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts|pageimages&exintro&explaintext&generator=search&gsrsearch=intitle:wikipedia&gsrlimit=1&redirects=1从Go Lang的Wikipedia API中获取JSON,>
我刚刚问了一个与此相关的问题,贡献者举了一个例子
https://play.golang.org/p/YjkTmrac0Sv
我更改了代码,但是由于从URL获得代码,因此无法正常工作。
我的代码旧代码:
type Wiki struct { Batchcomplete string `json:"batchcomplete"` Continue struct { Gsroffset int `json:"gsroffset"` Continue string `json:"continue"` } `json:"continue"` Query struct { Pages struct { Page struct { Pageid int `json:"pageid"` Ns int `json:"ns"` Title string `json:"title"` Index int `json:"index"` Extract string `json:"extract"` Thumbnail struct { Source string `json:"source"` Width int `json:"width"` Height int `json:"height"` } `json:"thumbnail"` Pageimage string `json:"pageimage"` } `json:"5043734"` } `json:"pages"` } `json:"query"` } wikipedia:="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts|pageimages&exintro&explaintext&generator=search&gsrsearch=intitle:wikipedia&gsrlimit=1&redirects=1" res, err := http.Get(wikipedia) if err != nil { panic(err.Error()) } body, err := ioutil.ReadAll(res.Body) if err != nil { panic(err.Error()) } var data Wiki // unmarshall json.Unmarshal(body, &data) //fmt.Printf("Results: %v\n", data) // print values of the object fmt.Printf("Title: " + data.Query.Pages.Page.Title) fmt.Printf("Extract: "+ data.Query.Pages.Page.Extract)
此代码有效,但是如果我更改搜索键,由于
json:"5043734"
,它不再起作用。有人告诉我改用Pages map[string]*struct
。
我的新代码:
type Wiki struct { Batchcomplete string `json:"batchcomplete"` Continue struct { Gsroffset int `json:"gsroffset"` Continue string `json:"continue"` } `json:"continue"` Query struct { Pages map[string]*struct { Pageid int `json:"pageid"` Ns int `json:"ns"` Title string `json:"title"` Index int `json:"index"` Extract string `json:"extract"` Thumbnail struct { Source string `json:"source"` Width int `json:"width"` Height int `json:"height"` } `json:"thumbnail"` Pageimage string `json:"pageimage"` } `json:"pages"` } `json:"query"` } wikipedia:="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts|pageimages&exintro&explaintext&generator=search&gsrsearch=intitle:wikipedia&gsrlimit=1&redirects=1" res, err := http.Get(wikipedia) if err != nil { panic(err.Error()) } body, err := ioutil.ReadAll(res.Body) if err != nil { panic(err.Error()) } var data Wiki // unmarshall json.Unmarshal(body, &data) //fmt.Printf("Results: %v\n", data) // print values of the object fmt.Printf("Title: " + data.Query.Pages.Title) fmt.Printf("Extract: "+ data.Query.Pages.Extract)
我需要根据给定的示例进行修改,但是我不知道该如何做。我尝试过但没有成功。
但是如果我将URL中的srsearch=intitle:wikipedia
更改为srsearch=intitle:Planet+Mars
,则由于ID而不再起作用。
我需要使用此URL从Go Lang的Wikipedia API中获取JSON,网址为https://en.wikipedia.org/w/api.php?format = json&action = query&prop = extracts | pageimages&exintro&explaintext&...
Pages
是一张地图。您可以在地图上查找页面:
for pageID, page := range data.Query.Pages {
fmt.Println(pageID, page.Title, page.Extract)
}