Home  >  Article  >  Backend Development  >  Why Does My Go Code Panic with a Runtime Error When Parsing a JSON Array with a Trailing Comma?

Why Does My Go Code Panic with a Runtime Error When Parsing a JSON Array with a Trailing Comma?

DDD
DDDOriginal
2024-10-28 08:13:29886browse

Why Does My Go Code Panic with a Runtime Error When Parsing a JSON Array with a Trailing Comma?

Runtime Error in JSON Array Parsing with Trailing Commas in Go

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?

The Resolution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn