As mentioned in this StackOverflow question, you are not allowed to have any trailing commas in json. For example, this

{
    "key1": "value1",
    "key2": "value2"
}

is fine, but this

{
    "key1": "value1",
    "key2": "value2",
}

is invalid syntax.

出于this other StackOverflow question中提到的原因,使用逗号结尾是合法的(也许是受鼓励的?)在Python代码中.我同时使用Python和JSON,所以我希望能够在这两种类型的文件中保持一致.有没有办法让json.loads忽略尾随的逗号?

推荐答案

可以将python的json解析器包装为jsoncomment

JSON Comment allows to parse JSON files or strings with:

  • 单行和多行注释
  • 多行数据字符串
  • 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相关问答推荐

2020-12年草案中的Json列举模式

JSON:将项';S键/名称移动到属性中,并使用JQ将其转换为数组

如何在Vega中使标记的符号在鼠标指针悬停时可点击

在 NX 工作区中跨多个应用共享 ngx-translate 翻译文件

NiFi 使用嵌套数组将 avro 转换为 JSON 数组格式

向 JSON 文件添加注释

Json.NET SerializeObject 转义值以防止 XSS

如何使用 gson 将数据保存在 json 文件中?

为什么在测试 RSPEC 时 JBuilder 不返回 JSON 中的响应正文

如何使用 Newtonsoft.Json 反序列化 JSON 数组

从多维数组数据生成json字符串

Django - 异常处理最佳实践和发送自定义错误消息

Spring MVC控制器中的JSON参数

json和空数组

在 JSON.stringify() 的输出中隐藏空值

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?

as_json 没有在关联上调用 as_json

使用 C# 调用 json

Javascript:如何判断 AJAX 响应是否为 JSON

如果键可能不存在,则从 Python dict 读取