解析带有尾随逗号的 JSON 数组和地图元素时出现运行时错误
Runtime error when parsing JSON array and map elements with trailing commas
Dave Cheney,围棋领域的主要主题专家之一,写道:"When initializing a variable with a composite literal, Go requires that each line of the composite literal end with a comma, even the last line of your declaration. This is the result of the semicolon rule."
然而,当我试图将这个漂亮的规则应用到 JSON 文本时,解析器似乎并不同意这种理念。在下面的代码中,删除逗号有效。是否有解决此问题的方法,以便在差异中添加元素时我只能看到一行更改?
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
}
没有。 JSON specification 不允许尾随逗号。
这不是有效的 JSON:
{ "objects":
[
{"name": "foo"},
]}
这是Go语法,如果枚举没有在行()上结束,则需要使用逗号,例如:
// Slice literal:
s := []int {
1,
2,
}
// Function call:
fmt.Println(
"Slice:",
s,
)
即使您可以 "convince" 一个特定的 JSON 解析器默默地吞下它,其他有效的 JSON 解析器也会报告错误,这是理所当然的。别这样。
虽然尾随逗号无效 JSON,但某些语言本身支持尾随逗号,特别是 JavaScript,因此您可能会在数据中看到它们。
最好删除尾随逗号,但如果您无法更改数据,请使用支持尾随逗号的 JSON 解析器,例如支持 HuJSON(又名 Human JSON) JSON 中的尾随逗号和注释。它是 encoding/json
和 is maintained by noted Xoogler and Ex-Golang team member Brad Fitzpatrick 以及其他人的软分叉。
Unmarshal
语法与encoding/json
相同,只需使用:
err := hujson.Unmarshal(data, v)
我已经用过了,效果和描述的一样。
Dave Cheney,围棋领域的主要主题专家之一,写道:"When initializing a variable with a composite literal, Go requires that each line of the composite literal end with a comma, even the last line of your declaration. This is the result of the semicolon rule."
然而,当我试图将这个漂亮的规则应用到 JSON 文本时,解析器似乎并不同意这种理念。在下面的代码中,删除逗号有效。是否有解决此问题的方法,以便在差异中添加元素时我只能看到一行更改?
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
}
没有。 JSON specification 不允许尾随逗号。
这不是有效的 JSON:
{ "objects":
[
{"name": "foo"},
]}
这是Go语法,如果枚举没有在行(
// Slice literal:
s := []int {
1,
2,
}
// Function call:
fmt.Println(
"Slice:",
s,
)
即使您可以 "convince" 一个特定的 JSON 解析器默默地吞下它,其他有效的 JSON 解析器也会报告错误,这是理所当然的。别这样。
虽然尾随逗号无效 JSON,但某些语言本身支持尾随逗号,特别是 JavaScript,因此您可能会在数据中看到它们。
最好删除尾随逗号,但如果您无法更改数据,请使用支持尾随逗号的 JSON 解析器,例如支持 HuJSON(又名 Human JSON) JSON 中的尾随逗号和注释。它是 encoding/json
和 is maintained by noted Xoogler and Ex-Golang team member Brad Fitzpatrick 以及其他人的软分叉。
Unmarshal
语法与encoding/json
相同,只需使用:
err := hujson.Unmarshal(data, v)
我已经用过了,效果和描述的一样。