Skip to content

Instantly share code, notes, and snippets.

@MohanSha
Forked from qeubar/main.go
Created February 12, 2021 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MohanSha/a7a62c526712a4275a45218502ea4070 to your computer and use it in GitHub Desktop.
Save MohanSha/a7a62c526712a4275a45218502ea4070 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