我能否在以下发言中发表一些意见?Json Json (Json Json) (Json Json Json) (Json Json) Json Json (Json Json) Json (Json) Json (Json) Json (Json) Json (Json) Json (Json) Json (Json) Json(Json) Json (Json) Json (Json) Json(Json) Json (Json) Json如果有,如何处理?


当前回答

如果您正在使用 PHP, 您可以使用此函数搜索并删除 JSON 字符串中的 / / / * 键入批注, 然后将其解析成对象/ 数组 :

function json_clean_decode($json, $assoc = true, $depth = 512, $options = 0) {
       // search and remove comments like /* */ and //
       $json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);

       if(version_compare(phpversion(), '5.4.0', '>=')) {
           $json = json_decode($json, $assoc, $depth, $options);
       }
       elseif(version_compare(phpversion(), '5.3.0', '>=')) {
           $json = json_decode($json, $assoc, $depth);
       }
       else {
           $json = json_decode($json, $assoc);
       }

       return $json;
   }

希望这有帮助!

其他回答

我们正在使用strip-json-comments支持我们的项目。 它支持一些东西,比如:

/*
 * Description 
*/
{
    // rainbows
    "unicorn": /* ❤ */ "cake"
}

简简npm install --save strip-json-comments安装和使用它如下:

var strip_json_comments = require('strip-json-comments')
var json = '{/*rainbows*/"unicorn":"cake"}';
JSON.parse(strip_json_comments(json));
//=> {unicorn: 'cake'}

在JSON的输出之前,我需要将评论用于调试目的。所以我把调试信息放进HTTP 信头为了避免客户被打破:

header("My-Json-Comment: Yes, I know it's a workaround ;-) ");

Enter image description here

如果您的上下文是 NOde.js 配置, 您可以考虑 JavaScript 通过module.exports作为JSON的替代:

module.exports = {
    "key": "value",

    // And with comments!
    "key2": "value2"
};

缩略require语法将保持不变 。 作为 JavaScript, 文件扩展名应该是.js.

JSON并不支持本地的评论, 但您可以自己制作解码器或至少预处理器来删除评论, 这完全没问题(只要您只是忽略评论, 不使用它们来指导您的应用程序如何处理 JSON 数据 ) 。

JSON没有评论。 JSON 编码器必须输入输出评论。 JSON 编码器可能接受和忽略评论。

评论绝不应被用来传递任何有意义的信息。这就是JSON的目的。

参 :Douglas Crockford,Json Spec的作者,道格拉斯·克罗克福德.

纯粹的答案是否 无.

但有些编辑和平台利用变通办法向JSON提供评论。

1今天,大多数编辑都有内在的选择和扩展,以补充对JSON文件的评论。 (例如: - VS 代码还有一个带有评论的JSON。(jsonc) mode《VS法典》也有很好的展期)

VsCode 中激活 jsonc 模式的链接

2一些平台为补充评论(简简json)提供了内在途径。 (例如:- 在消防基地,我可以评论firebase.json暂时没有问题。

    {
    "hosting": {
        "headers": [
            /*{
              "source": "*.html",
              "headers": [
                {
                  "key": "Content-Security-Policy",
                  "value": "default-src 'self' ..."
                }
              ]
            },*/
        ]
      }
    }

3。在您自己的 JSON 解析方法中,您可以设置一个预定义的密钥名称作为注释。

包括:-

     {
        "comment" : "This is a comment",
        "//" :  "This also comment",
        "name" : "This is a real value"
     }