我可以在json文件里使用注释吗? 如果是的话,怎么写?
当前回答
*.json文件通常用作配置文件或静态数据,因此需要评论 * 一些像Netbeans这样的编辑在 *.json中接受评论。
问题在于将内容解析到对象上。 解决办法是总是应用清洁功能( 服务器或客户端 ) 。
php /p
$rgx_arr = ["/\/\/[^\n]*/sim", "/\/\*.*?\*\//sim", "/[\n\r\t]/sim"];
$valid_json_str = \preg_replace($rgx_arr, '', file_get_contents(path . 'a_file.json'));
手笔
valid_json_str = json_str.replace(/\/\/[^\n]*/gim,'').replace(/\/\*.*?\*\//gim,'')
其他回答
我真的很喜欢 @eli ' s 方法, 有超过 30 个答案, 但没有人提到列表( array) 。 所以使用 @eli ' s 方法, 我们可以做类似的事情:
"part_of_speech": {
"__comment": [
"@param {String} type - the following types can be used: ",
"NOUN, VERB, ADVERB, ADJECTIVE, PRONOUN, PREPOSITION",
"CONJUNCTION, INTERJECTION, NUMERAL, PARTICLE, PHRASE",
"@param {String} type_free_form - is optional, can be empty string",
"@param {String} description - is optional, can be empty string",
"@param {String} source - is optional, can be empty string"
],
"type": "NOUN",
"type_free_form": "noun",
"description": "",
"source": "https://google.com",
"noun_class": {
"__comment": [
"@param {String} noun_class - the following types can be used: ",
"1_class, 2_class, 3_class, 4_class, 5_class, 6_class"
],
"noun_class": "4_class"
}
}
我们用脱衣配对来做我们的项目。 它支持一些东西,比如:
/*
* 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'}
我刚刚找到了"咕噜咕噜咕噜咕噜声"
“从json那里提取评论, 让你在json档案中使用评论!”
{
// Rainbows
"unicorn": /* ❤ */ "cake"
}
您可以通过正则表达式使用简单的预处理。例如,以下函数将在php中解码注释json:
function json_decode_commented ($data, $objectsAsArrays = false, $maxDepth = 512, $opts = 0) {
$data = preg_replace('~
(" (?:[^"\\\\] | \\\\\\\\ | \\\\")*+ ") | \# [^\v]*+ | // [^\v]*+ | /\* .*? \*/
~xs', '$1', $data);
return json_decode($data, $objectsAsArrays, $maxDepth, $opts);
}
它支持所有php- type 注释 : / *, , , / / 。 字符串的字典被保存 。
如果您使用 json5, 您可以包含注释 。
json5建议扩展至json, 目的是使人类更容易手写和保持。
推荐文章
- 在VS Code中禁用“Comments are not allowed In JSON”错误
- 如何在Kotlin解析JSON ?
- JSON文件的蒙古导入
- 如何用jQuery / JavaScript解析JSON数据?
- jQuery在请求体中发布有效的json
- 将JSON显示为HTML
- Swift:理解// MARK
- 在JSON键名中哪些字符是有效的/无效的?
- 如何JSON序列化集?
- 如何检查JSON键是否存在?
- 在构建中编写注释的语法是什么?gradle文件?
- 将对象序列化为JSON
- node.js TypeError:路径必须是绝对路径或指定根路径到res.sendFile[解析JSON失败]
- Python json。loads显示ValueError:额外数据
- JSON省略了Infinity和NaN;JSON在ECMAScript中的状态?