Home >Backend Development >Golang >Trailing Commas in JSON: Why Does Go\'s Composite Literal Syntax Conflict with JSON Parsing?
Dave Cheney, a renowned expert on Go, emphasizes the requirement for trailing commas in composite literal declarations. However, this rule seems to conflict with JSON parsing.
Consider the following code:
<code class="go">// package, imports omitted for brevity type jsonobject struct { Objects []ObjectType `json:"objects"` } type ObjectType struct { Name string `json:"name"` } func main() { bytes := []byte(`{ "objects": [ {"name": "foo"}, // REMOVE THE COMMA TO MAKE THE CODE WORK! ]}`) jsontype := &jsonobject{} json.Unmarshal(bytes, &jsontype) fmt.Printf("Results: %v\n", jsontype.Objects[0].Name) // panic: runtime error: index out of range }</code>
Removing the trailing comma resolves the runtime error. Does Go support a fix for this inconsistency?
Unfortunately, there is no solution. The JSON specification does not permit trailing commas. While Go syntax mandates trailing commas in composite literals, this requirement does not apply to JSON parsing.
In other words, the following JSON is invalid:
<code class="json">{ "objects": [ {"name": "foo"}, ]}</code>
Despite the potential for a specific JSON parser to ignore the trailing comma, this practice should be avoided as it may cause errors when using other valid JSON parsers.
The above is the detailed content of Trailing Commas in JSON: Why Does Go\'s Composite Literal Syntax Conflict with JSON Parsing?. For more information, please follow other related articles on the PHP Chinese website!