json.loads 可以忽略尾随逗号吗? [英] Can json.loads ignore trailing commas?

查看:32
本文介绍了json.loads 可以忽略尾随逗号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 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 注释允许解析 JSON 文件或字符串:

JSON Comment allows to parse JSON files or strings with:

  • 单行和多行注释
  • 多行数据字符串
  • 对象和数组中的尾随逗号,在最后一项之后

示例用法:

import json
from jsoncomment import JsonComment

with open(filename) as data_file:    
    parser = JsonComment(json)
    data = parser.load(data_file)

这篇关于json.loads 可以忽略尾随逗号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆