我有一个 json 文件,如下所示:
{
"author":"John",
"desc": "If it is important to decode all valid JSON correctly \
and speed isn't as important, you can use the built-in json module, \
orsimplejson. They are basically the same but sometimes simplej \
further along than the version of it that is included with \
distribution."
//"birthday": "nothing" //I comment this line
}
该文件是由另一个程序自动创建的。我如何用 Python 解析它?
原文由 BollMose 发布,翻译遵循 CC BY-SA 4.0 许可协议
我无法想象一个 “由其他程序自动创建” 的 json 文件会在里面包含注释。因为 json 规范 根本没有定义注释,这是 设计 使然,所以没有 json 库会输出带有注释的 json 文件。
这些评论通常是稍后由人工添加的。在这种情况下也不例外。 OP 在他的帖子中提到:
//"birthday": "nothing" //I comment this line
。所以真正的问题应该是,我如何正确地注释 json 文件中的某些内容,同时保持其符合规范并因此与其他 json 库兼容?
答案是,将您的字段重命名为另一个名称。例子:
可以改成:
这在大多数情况下都可以正常工作,因为消费者很可能会忽略意外字段(但并非总是如此,这取决于您的 json 文件消费者的实现。所以 YMMV。)
更新:显然有些读者不高兴,因为这个答案没有给出他们期望的“解决方案”。好吧,事实上,我确实通过隐式链接到 JSON 设计者的引用 提供了一个可行的解决方案:
所以,是的,继续使用 JSMin 。请记住,当您走向“在 JSON 中使用注释”时,这是一个概念上未知的领域。不能保证您选择的任何工具都可以处理:内联
[1,2,3,/* a comment */ 10]
,Python 样式[1, 2, 3] # a comment
(这是 Python 中的注释,但不是 Javascript 中的注释),INI 样式[1, 2, 3] ; a comment
, …, 你明白了。我仍然建议首先不要在 JSON 中添加不合规的注释。