JSON注释
之所以不允许添加注释,是因为 JSON 主要是用来存储数据的,过多的注释会对数据的可读性造成影响,同时也会造成数据体积变大,进而影响数据传输、解析的速度。
但是,在某些场景中,我们又需要使用注释。例如在 JSON 格式的配置文件中,我们希望以注释的形式对配置信息进行解释说明;在接口返回的 JSON 数据中,我们希望通过注释描述数据的含义等等。那么我们要怎么在 JSON 数据中添加注释呢?下面就来介绍几种方法。
使用特殊的键名
想要在 JSON 中添加注释,我们可以在要添加注释键/值对的前面(或后面)添加一个同名的键,并在键名中添加一个特殊字符加以区分,例如 @
、#
、?
、_
、/
等,然后在与键对应的值中定义注释的内容。注意:在键名中添加特殊字符时,应尽量避免 :
、{
、}
、[
、]
等 JSON 中常用的字符。
下面通过一个简单的示例来演示一下如何通过特殊的键名在 JSON 中添加注释:
{
"@name": "网站名称",
"name": "C语言中文网",
"_url": "网址",
"url": "http://c.biancheng网站站点" rel="nofollow" />
{
"_comment": "C语言中文网(http://c.biancheng网站站点" rel="nofollow" />
{
// 网站名称
"name": "C语言中文网",
// 网址
"url": "http://c.biancheng网站站点" rel="nofollow" />
<script src="https://unpk网站站点" rel="nofollow" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<script src="https://unpk网站站点" rel="nofollow" />
图:在网页中引用 JSON5
此外,您也可以通过 Node.js 来安装 JSON5,安装令如下:
npm install json5
安装成功后可以通过 const JSON5 = require('json5')
来创建全局的 JSON5 对象,如下例所示:C:\Users\79330>npm install json5
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\79330\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\79330\package.json'
npm WARN 79330 No description
npm WARN 79330 No repository field.
npm WARN 79330 No README data
npm WARN 79330 No license field.
+ json5@2.2.0
added 2 packages from 5 contributors and audited 2 packages in 2.525s
found 0 vulnerabilities
C:\Users\79330>node
Welcome to Node.js v14.17.6.
Type ".help" for more information.
> const JSON5 = require('json5')
undefined
> var arr = {
... // 网站名称
... "name": "C语言中文网",
... // 网址
... "url": "http://c.biancheng网站站点" rel="nofollow" />