This is my first attempt, as a Go newbee, to access deeply nested values from a JSON file generated by the Wikipedia API using Go structs. Reading through all threads concerning Unmarshaling with Go didn't help much.
Json sample file (extracted from the Wikipedia API)
{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "Go_(programming_language)",
"to": "Go (programming language)"
}
],
"pages": {
"25039021": {
"pageid": 25039021,
"ns": 0,
"title": "Go (programming language)",
"extract": "Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson."
}
}
}
}
I want to access the values of title
and extract
. Its trivial using jq
:
$ jq '.query.pages[] | .title, .extract' wikipedia-api-output
"Go (programming language)"
"Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson."
my latest failed attempt in go:
type Wiki struct {
Query struct {
Pages struct {
Article struct {
Title string `json:"title`
Extract string `json:"extract`
} `json:"25039021"`
} `json:"pages"`
} `json:"query"`
}
func main() {
jsonStr :=
`{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "Go_(programming_language)",
"to": "Go (programming language)"
}
],
"pages": {
"25039021": {
"pageid": 25039021,
"ns": 0,
"title": "Go (programming language)",
"extract": "Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson."
}
}
}
}`
var wikiDescr Wiki
err := json.Unmarshal([]byte(jsonStr), &wikiDescr)
if err != nil {
fmt.Println(err)
}
fmt.Println(wikiDescr)
}
This returns the expected result, but the pageid
(25039021) used to extract the required values is generated by Wikipedia and can not be guessed. Is there a way to wildcard that value or do I need to extract that pageid
value first and then use it like in the code above?