go - Runtime error when parsing JSON array and map elements with trailing commas -


dave cheney, 1 of leading subject matter experts on go, wrote: "when initializing variable composite literal, go requires each line of composite literal end comma, last line of declaration. result of semicolon rule."

however, when trying apply beautiful rule json text, parser doesn't seem agree philosophy. in code below, removing comma works. there fix can see 1 line change when add elements in diffs?

package main  import (     "fmt"     "encoding/json" )  type jsonobject struct {     objects []objecttype `json:"objects"` }  type objecttype struct {     name string `json:"name"` }  func main() {     bytes := []byte(`{ "objects":          [              {"name": "foo"}, // remove comma make code work!         ]}`)     jsontype := &jsonobject{}     json.unmarshal(bytes, &jsontype)     fmt.printf("results: %v\n", jsontype.objects[0].name) // panic: runtime error: index out of range } 

there not. json specification not allow trailing comma.

this not valid json:

{ "objects":      [          {"name": "foo"}, ]} 

it's go syntax need use comma if enumeration not closed on line (more on this), e.g.:

// slice literal: s := []int {     1,     2, }  // function call: fmt.println(     "slice:",     s, ) 

even if "convince" 1 specific json parser silently swallow it, other, valid json parsers report error, rightfully. don't it.


Comments