-
-
Save MohanSha/a7a62c526712a4275a45218502ea4070 to your computer and use it in GitHub Desktop.
Parse top-level json array in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Some json APIs tend to present list responses in | |
a single array not wrapped in the usual { "results" :[] } style. | |
Below is a simple way of parsing [ { ... }, { ... }, ... ] json responses. | |
*/ | |
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type Product struct { | |
Id int `json:"id"` | |
Name string `json:"name"` | |
} | |
func main() { | |
productsList := []byte(`[{"id": 1,"name": "gold"},{"id": 2,"name": "silver"},{"id": 3,"name": "bronze"}]`) | |
var products []Product | |
json.Unmarshal(productsList, &products) | |
fmt.Printf("%v", products) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment