json.loads可以忽略尾随逗号吗? [英] Can json.loads ignore trailing commas?
问题描述
如此StackOverflow问题中所述,则不允许在json中使用任何结尾的逗号.例如,这个
As mentioned in this StackOverflow question, you are not allowed to have any trailing commas in json. For example, this
{
"key1": "value1",
"key2": "value2"
}
很好,但这
{
"key1": "value1",
"key2": "value2",
}
语法无效.
出于其他StackOverflow问题中提到的原因,使用逗号结尾是合法的(也许鼓励?)在Python代码中.我同时使用Python和JSON,因此我希望能够在两种类型的文件之间保持一致.有没有办法让json.loads
忽略尾随逗号?
For reasons mentioned in this other StackOverflow question, using a trailing comma is legal (and perhaps encouraged?) in Python code. I am working with both Python and JSON, so I would love to be able to be consistent across both types of files. Is there a way to have json.loads
ignore trailing commas?
推荐答案
您可以使用 jsoncomment包装python的json解析器
JSON Comment允许使用以下命令解析JSON文件或字符串:
JSON Comment allows to parse JSON files or strings with:
- 单行和多行注释
- 多行数据字符串
- 在最后一项之后的对象和数组中尾随逗号
- Single and Multi line comments
- Multi line data strings
- Trailing commas in objects and arrays, after the last item
示例用法:
import json
from jsoncomment import JsonComment
with open(filename) as data_file:
parser = JsonComment(json)
data = parser.load(data_file)
这篇关于json.loads可以忽略尾随逗号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!