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

推荐答案

我无法想象json文件"auto created by other program"会包含注释.因为json spec完全不定义注释,也就是by design,所以没有json库会输出带有注释的json文件.

这些 comments 通常是稍后由人添加的.在这种情况下也不例外.操作员在他的帖子中提到了这一点://"birthday": "nothing" //I comment this line.

So the real question should be, how do I properly comment some content in a json file, yet maintaining its compliance with spec and hence its compatibility with other json libraries?

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

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

可以更改为:

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

This will work just fine most of the time because the consumer will very likely ignore unexpected fields (but not always, it depends on your json file consumer's implementation. So YMMV.)

UPDATE:显然,一些读者不高兴,因为这个答案没有给出他们期望的"解决方案".事实上,我确实给出了一个有效的解决方案,通过隐式链接到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.

So, yeah, go ahead to use JSMin. Just keep in mind that when you are heading towards "using comments in JSON", that is a conceptually uncharted territory. There is no guarantee that whatever tools you choose would handle: inline [1,2,3,/* a comment */ 10], Python style [1, 2, 3] # a comment (which is a comment in Python but not in Javascript), INI style [1, 2, 3] ; a comment, ..., you get the idea.

我仍然建议首先不要在JSON中添加不一致的注释.

Json相关问答推荐

使用自定义类型在Golang中解析JSON数组

无法使用Jolt变换在嵌套的JSON中提取值

对一些JSON模式验证的混淆

使用 Redis 作为键值存储

XSLT 3.0 Json-to-xml,json 包含 html struct

Golang jsonrpc2 服务器在哪里监听?

如何强制仅有一个元素的数组在JSON中生成方括号

如何从 json 中获取单个元素?

如何在循环中传递列表(会话(字符串属性))以在 Gatling Scala 中创建批量 Json 请求

如何为包含一些固定值并可能具有其他附加值的数组字符串创建数组 json 架构

Servicestack 返回数组而不是带有数组的对象

使用 jq 同时迭代数组

Golang / Go - 如果 struct 没有字段,如何将其编组为空?

将 YAML 文件转换为 Python JSON 对象

如何通过 NSJSONSerialization 在 JSON 中包含空值?

在 Postgres 中向 JSON 对象添加元素

jQuery JSON 响应总是触发 ParseError

json_encode() 返回 false

杰克逊在通用列表中读取 json

如何向 json IAM 策略添加 comments ?