4 ms·
How about an array of Media? package main import ( "encoding/json" "fmt" ) type Media struct { Title string
by Zikes 12y ago
How about an array of Media?
package main
import (
"encoding/json"
"fmt"
)
type Media struct {
Title string
Price float64
PurchaseType string
}
func main() {
jsonData := []byte(`
[
{"purchaseType":"Rent","price":0.99,"title":"Inception"},
{"purchaseType":"Free","price":0.00,"title":"Johnny Mnemonic"},
{"purchaseType":"Buy","price":17.99,"title":"John Wick"}
]
`)
var media []Media
err := json.Unmarshal(jsonData, &media)
if err != nil {
fmt.Println("error: ", err)
}
fmt.Printf("%+v\n", media)
}
Output:
$ go run main.go
[{Title:Inception Price:0.99 PurchaseType:Rent}
{Title:Johnny Mnemonic Price:0 PurchaseType:Free}
{Title:John Wick Price:17.99 PurchaseType:Buy}]
Edit: Regarding the MediaType: http://stackoverflow.com/questions/14426366/what-is-an-idiomatic-way-of-representing-enums-in-golang http://stackoverflow.com/questions/14426366/what-is-an-idiom...
- codygman 12y agoCheck out my update if you haven't seen it already. tl;dr The problem for me personally is when you start making functions based on the type of media and sacrifice type safety if MediaType is a string.
- sagichmal 12y agoPurchaseType doesn't need to be stringly typed. See https://talks.golang.org/2015/json.slide#1 https://talks.golang.org/2015/json.slide#1. type PurchaseType byte const ( Free PurchaseType = iota Rent Buy ) func (t *PurchaseType) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return fmt.Errorf("purchase type should be a string, got %s", data) } have, ok := map[string]PurchaseType{"Free": Free, "Rent": Rent, "Buy": Buy}[s] if !ok { return fmt.Errorf("invalid purchase type %q", s) } *t = have return nil } That's enough to give this output: [{Inception 0.99 Rent} {Johnny Mnemonic 0 Free} {John Wick 17.99 Buy}] http://play.golang.org/p/dyNVlgmFtu http://play.golang.org/p/dyNVlgmFtu