Home >Backend Development >Golang >Why Does My Go Code Panic with a Runtime Error When Parsing a JSON Array with a Trailing Comma?
Dave Cheney, a renowned expert on Go, emphasizes the significance of ending each line of a composite literal with a comma. However, this rule seems to contradict with JSON parsing in Go.
Consider the following code:
<code class="go">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 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>
In this code, removing the trailing comma from the JSON array makes it work. However, isn't there a way to avoid this inconsistency?
Unfortunately, no. The JSON specification prohibits trailing commas. It is a valid Go syntax to add a trailing comma to an opened enumeration that continues on another line. However, this is not applicable to JSON.
Here's an example of an invalid JSON structure:
{ "objects": [ {"name": "foo"}, ]}
Even if it were possible to persuade a specific JSON parser to accept this format, other valid JSON parsers would rightly report an error. Therefore, it is recommended to adhere to the JSON specification and avoid trailing commas.
The above is the detailed content of Why Does My Go Code Panic with a Runtime Error When Parsing a JSON Array with a Trailing Comma?. For more information, please follow other related articles on the PHP Chinese website!