Created
February 25, 2017 00:08
-
-
Save qeubar/3c3152110e71ecf76e8384a8f46381b5 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