JSON中是否可以使用注释

JSON中是否可以使用注释

技术背景

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据传输。它以简洁的语法和易于解析的特点被广泛应用。然而,JSON最初的设计理念是仅用于表示数据,所以对于是否能在其中使用注释存在一定的争议。

实现步骤

官方标准

JSON官方标准中不支持//.../*...*/形式的注释。JSON的设计初衷是数据交换,注释被认为会破坏其互操作性,因此被从标准中移除。例如,JSON的官方规范文档(如RFC 8259)中并未提及注释相关内容。

变通方法

  • 使用指定数据元素:可以在JSON中添加一个名为"_comment"的数据元素来作为注释,不过使用该JSON数据的应用需要忽略这个元素。示例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"_comment": "comment text goes here...",
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
  • 利用重复键:在声明对象字面量时,可以指定两个相同键的值,JSON解析器会取最后一个值。可以利用这一特性创建注释,这些注释在解析后的对象中不会存在。示例如下:
1
2
3
4
5
6
7
8
9
10
{
"api_host": "The hostname of your API server. You may also specify the port.",
"api_host": "hodorhodor.com",
"retry_interval": "The interval in seconds between retrying failed API calls",
"retry_interval": 10,
"auth_token": "The authentication token. It is available in your developer dashboard under 'Settings'",
"auth_token": "5ad0eb93697215bc0d48a7b69aa6fb8b",
"favorite_numbers": "An array containing my all-time favorite numbers",
"favorite_numbers": [19, 13, 53]
}

支持注释的解析器

虽然标准不支持,但部分解析器支持添加注释:

  • JsonCpp:支持C++风格的注释。示例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
// 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 }
}
  • JSON5:是JSON的超集,支持C++风格的注释。示例如下:
1
2
3
4
5
6
// A single line comment.
/* A multi-
line comment. */
{
"key": "value"
}
  • Jackson:可以通过配置使其允许注释。示例代码如下:
1
2
3
4
5
6
7
8
9
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonParser.Feature;

public class Main {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_COMMENTS, true);
mapper.configure(Feature.ALLOW_YAML_COMMENTS, true);
}
}
  • Newtonsoft.Json:使用ASP.NET时,6+版本支持单行和多行注释。示例如下:
1
2
3
4
5
6
7
//"name": "string"
//"id": int
/* This is a
comment example */
{
"key": "value"
}

核心代码

使用JSON.minify()移除注释

1
2
3
4
5
6
7
8
const JSONminify = require('jsonminify');
const my_str = `{
// 这是一个注释
"key": "value"
}`;
const validJSON = JSONminify(my_str);
const parsedData = JSON.parse(validJSON);
console.log(parsedData);

最佳实践

  • 使用JSON Schema:可以编写JSON Schema来为JSON数据提供文档说明和验证。示例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"description": "A person",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"maximum": 125
}
}
}
  • 使用支持注释的JSON扩展:如JSON5,它既支持注释,又与JSON完全向后兼容。

常见问题

  • 解析器兼容性问题:使用非标准的注释方法可能导致部分解析器无法正确解析JSON数据,特别是流式解析器。因此,在选择注释方法时,需要考虑解析器的兼容性。
  • 网络带宽问题:如果在JSON文件中包含注释并进行网络传输,会增加数据量,浪费网络带宽。建议在传输前移除注释。

JSON中是否可以使用注释
https://119291.xyz/posts/2025-05-06.can-comments-be-used-in-json/
作者
ww
发布于
2025年5月6日
许可协议