"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Trailing Commas in JSON: Why Does Go\'s Composite Literal Syntax Conflict with JSON Parsing?

Trailing Commas in JSON: Why Does Go\'s Composite Literal Syntax Conflict with JSON Parsing?

Posted on 2025-03-23
Browse:339

  Trailing Commas in JSON: Why Does Go\'s Composite Literal Syntax Conflict with JSON Parsing?

Trailing Comma Syntax Error in JSON Parsing with Go

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:

// 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
}

Removing the trailing comma resolves the runtime error. Does Go support a fix for this inconsistency?

Solution

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:

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3