Skip to content

Instantly share code, notes, and snippets.

@qeubar
Created February 25, 2017 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save qeubar/3c3152110e71ecf76e8384a8f46381b5 to your computer and use it in GitHub Desktop.
Save qeubar/3c3152110e71ecf76e8384a8f46381b5 to your computer and use it in GitHub Desktop.
Parse top-level json array in Go
/*
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