Unmarshaling JSON Object Values

If a string is specified, from a MediaWiki API request:

str = ` { "query": { "pages": { "66984": { "pageid": 66984, "ns": 0, "title": "Main Page", "touched": "2012-11-23T06:44:22Z", "lastrevid": 1347044, "counter": "", "length": 28, "redirect": "", "starttimestamp": "2012-12-15T05:21:21Z", "edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\" } } } }` 

What can be done to get edittoken using the Go json package (remember, number 66984 will keep changing)?

+4
source share
2 answers

Note that if you use the &indexpageids=true parameter in the API URL, the result will contain an array of "pageids", for example:

 str = ` { "query": { "pageids": [ "66984" ], "pages": { "66984": { "pageid": 66984, "ns": 0, "title": "Main Page", "touched": "2012-11-23T06:44:22Z", "lastrevid": 1347044, "counter": "", "length": 28, "redirect": "", "starttimestamp": "2012-12-15T05:21:21Z", "edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\" } } } }` 

so that you can use pageids[0] to access an ever-changing number, which is likely to make things easier.

+4
source

When you have such an interchangeable key, the best way to deal with it is with a card. In the example below, I used structures until we reach a mutable key. Then I switched to map format. I also related a working example.

http://play.golang.org/p/ny0kyafgYO

 package main import ( "fmt" "encoding/json" ) type query struct { Query struct { Pages map[string]interface{} } } func main() { str := `{"query":{"pages":{"66984":{"pageid":66984,"ns":0,"title":"Main Page","touched":"2012-11-23T06:44:22Z","lastrevid":1347044,"counter":"","length":28,"redirect":"","starttimestamp":"2012-12-15T05:21:21Z","edittoken":"bd7d4a61cc4ce6489e68c21259e6e416+\\"}}}}` q := query{} err := json.Unmarshal([]byte(str), &q) if err!=nil { panic(err) } for _, p := range q.Query.Pages { fmt.Printf("edittoken = %s\n", p.(map[string]interface{})["edittoken"].(string)) } } 
+5
source

All Articles