我可以在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;
   }

希望这有帮助!

其他回答

这是一个"你能"的问题。 这是"可以"的答案。

否, 您不应该使用重复对象成员将侧通道数据塞进json 编码 。 (请参见 rfc 中“ 对象中的名称应该是独一无二的 ” ) 。

是的,你可以在json周围插入评论, 你可以分析出来。

但如果你想将任意的侧道数据插入和提取到一个有效的json 中, 请使用一个答案 。 我们利用 Json 编码中的数据非独有的表达方式。 在 rfc 的第二节中, “ 允许在六个结构字符中的任何字符之前或之后使用白色空间 ” 。

* rfc 仅表示“在六个结构字符之前或之后允许有白色空间”,但没有明确提及字符串、数字、“假”、“真”和“null”。 在所有执行中,这一遗漏被忽略。


首先,将你的json拼写成拼写:

$jsonMin = json_encode(json_decode($json));

然后将您的评论编码为二进制 :

$hex = unpack('H*', $comment);
$commentBinary = base_convert($hex[1], 16, 2);

然后输入您的二进制 :

$steg = str_replace('0', ' ', $commentBinary);
$steg = str_replace('1', "\t", $steg);

您的输出 :

$jsonWithComment = $steg . $jsonMin;

确定您可以对 json 进行评论。 从 javascript 读取 json 注释文件, 您可以在解析前删除评论( 参见下面的代码) 。 我确信这个代码可以改进, 但对于使用常规表达式的人来说很容易理解 。

我使用备受评论的json文件来指定我的合成反射系统 的神经元形状。 我也使用备受评论的json 来储存一个运行中的神经元系统的中间状态。 方便地得到评论。 不要听那些告诉你他们是个坏主意的人。

fetch(filename).then(function(response) {
    return response.text();
}).then(function(commented) {
    return commented.
        replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '$1').
        replace(/\r/,"\n").
        replace(/\n[\n]+/,"\n");
}).then(function(clean) {
    return JSON.parse(clean);
}).then(function(json) {
    // Do what you want with the JSON object.
});

您应该撰写json schema。json schema目前是一份拟议互联网规格草案。除文档外,该schema还可以用于验证您的json数据 。

例如:

{
  "description": "A person",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer",
      "maximum": 125
    }
  }
}

您可以使用描述 schema 属性提供文档。

注释不是官方标准,尽管有些分析者支持 c++- 风格的注释。

// Configuration options
{
    // Default encoding for text
    "encoding" : "UTF-8",

    // Plug-ins loaded at start-up
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],

    // Tab indent size
    "indent" : { "length" : 3, "use_space": true }
}

jsonlint 不验证这一点 。 因此, 批注是解析器特定的扩展名, 而不是标准 。

另一本书是Json5。

取代json Toml的替代品。

另一种选择是jsonc。

Nlohmann/json的最新版本有选择的支持,

我们用脱衣配对来做我们的项目。 它支持一些东西,比如:

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

简单的 npm 安装 -- save 条形引言,用于安装和使用它,例如:

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