Home > Backend Development > Golang > 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?

DDD
Release: 2024-10-28 20:17:31
Original
398 people have browsed it

  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:

<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>
Copy after login

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:

<code class="json">{ "objects": 
    [ 
        {"name": "foo"},
]}</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template