如 this StackOverflow question 中所述, json 中不允许有任何尾随逗号。比如这个
{
"key1": "value1",
"key2": "value2"
}
很好,但是这个
{
"key1": "value1",
"key2": "value2",
}
语法无效。
由于 this other StackOverflow question 中提到的原因, 在 Python 代码中使用尾随逗号是合法的(也许是鼓励的?)。我正在使用 Python 和 JSON,所以我希望能够在这两种类型的文件中保持一致。有没有办法让 json.loads
忽略尾随逗号?
最佳答案
快进到 2021 年,现在我们有了 https://pypi.org/project/json5/
引用自链接:
A Python implementation of the JSON5 data format.
JSON5 extends the JSON data interchange format to make it slightly more usable as a configuration language:
- JavaScript-style comments (both single and multi-line) are legal.
- Object keys may be unquoted if they are legal ECMAScript identifiers
- Objects and arrays may end with trailing commas.
- Strings can be single-quoted, and multi-line string literals are allowed.
用法与python内置的json模块一致:
>>> import json5
>>> json5.loads('{"key1": "{my special value,}",}')
{u'key1': u'{my special value,}'}
它确实带有警告:
Known issues
- Did I mention that it is SLOW?
加载启动配置等足够快。
https://stackoverflow.com/questions/23705304/
相关文章:
java - 如何测试 JSONObject 是否为空或不存在
ruby-on-rails - JBuilder中未定义的局部变量或方法 `json'
javascript - 将 JSON 对象推送到 localStorage 中的数组
ajax - 何时将 Ajax 与 Json 用于 Javascript 事件?
json - 有什么方法可以在运行时使用 webpack 加载资源?
javascript - JSON 无法解析的垃圾 : Why so serious?
python - IPython Notebook 中漂亮的 JSON 格式
javascript - 如何从对象中删除所有 null 和空字符串值?