如何解析带有c风格注释的json文件?

2024-05-09 19:02:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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解析它?


Tags: 文件thetojsonifisitall
3条回答

我没有亲自使用过它,但是jsoncommentpython包支持解析带有注释的JSON文件。

使用它代替JSON解析器,如下所示:

parser = JsonComment(json)
parsed_object = parser.loads(jsonString)

我无法想象由其他程序自动创建的json文件会包含注释。因为json spec根本不定义注释,也就是by design,所以任何json库都不会输出带有注释的json文件。

这些评论通常是后来由人添加的。在这种情况下没有例外。这位专栏作家在他的文章中提到://"birthday": "nothing" //I comment this line

所以真正的问题应该是,如何正确地注释json文件中的某些内容,同时保持其与spec的兼容性,从而保持与其他json库的兼容性?

答案是,将字段重命名为另一个名称。示例:

{
    "foo": "content for foo",
    "bar": "content for bar"
}

可以更改为:

{
    "foo": "content for foo",
    "this_is_bar_but_been_commented_out": "content for bar"
}

这在大多数情况下都会很好地工作,因为使用者很可能会忽略意外字段(但并不总是如此,这取决于json文件使用者的实现)。所以YMMV.)

更新:显然有些读者不满意,因为这个答案没有给出他们期望的“解决方案”。实际上,我确实给出了一个有效的解决方案,通过隐式链接到JSON designer's quote

Douglas Crockford Public Apr 30, 2012 Comments in JSON

I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.

Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.

所以,是的,继续使用JSMin。请记住,当您走向“使用JSON中的注释”时,这是一个概念上未知的领域。不保证您选择的任何工具都能处理:inline[1,2,3,/* a comment */ 10]、Python样式[1, 2, 3] # a comment(这是Python中的注释,但不是Javascript中的注释)、INI样式[1, 2, 3] ; a comment,…,您就得到了这个想法。

我仍然建议首先不要在JSON中添加不符合的注释。

jsoncomment很好,但不支持内联注释。

签出jstyleson,它支持

  • 内联注释
  • 单行注释
  • 多行注释
  • 尾随逗号。

示例

安装

pip install jstyleson

用法

import jstyleson
result_dict = jstyleson.loads(invalid_json_str) # OK
jstyleson.dumps(result_dict)

相关问题 更多 >