我可以在json文件里使用注释吗? 如果是的话,怎么写?
当前回答
在我目前的项目中,我遇到了这个问题, 因为我有相当多的json 需要一些评论 使事情容易记住。
i've used this simple python 函数来替换批注并使用 json. loads 将其转换成 dict:
import json, re
def parse_json(data_string):
result = []
for line in data_string.split("\n"):
line = line.strip()
if len(line) < 1 or line[0:2] == "//":
continue
if line[-1] not in "\,\"\'":
line = re.sub("\/\/.*?$", "", line)
result.append(line)
return json.loads("\n".join(result))
print(parse_json("""
{
// This is a comment
"name": "value" // so is this
// "name": "value"
// the above line gets removed
}
"""))
其他回答
注释不是官方标准,尽管有些分析者支持 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的最新版本有选择的支持,
至少这是我在Json. org的一眼 所经历的
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;
}
希望这有帮助!
您可以通过正则表达式使用简单的预处理。例如,以下函数将在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 注释 : / *, , , / / 。 字符串的字典被保存 。
(hack)是一个很好的解决办法(hack),这是有效的json,但并非在所有情况下都能奏效(见下文的评论)。
{
"param" : "This is the comment place",
"param" : "This is value place",
}
所以json会理解这一点:
{
"param" : "This is value place",
}
推荐文章
- 查询JSON类型内的数组元素
- 将JSON字符串转换为HashMap
- 将JsonNode转换为POJO
- Json_encode()转义正斜杠
- 如何写一个JSON文件在c# ?
- 在序列化和反序列化期间JSON属性的不同名称
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- Ajax会调用什么样的响应,比如'for (;;);{json data}的意思?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 使用Jackson将JSON字符串转换为漂亮的打印JSON输出
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 用c#解析JSON
- 如何合并2 JSON对象从2个文件使用jq?
- 在VS Code中禁用“Comments are not allowed In JSON”错误
- 如何在Kotlin解析JSON ?