JSON is an excellent data format, but we think it can be better
什么是 JSON5
JSON5 是对 JSON 的一种推荐扩展,旨在使人类更易于手动编写和维护。 它通过直接从 ECMAScript 5 添加一些最小的语法功能来实现这一点。
JSON5 仍然是 JavaScript 的严格子集,不添加任何新的数据类型,并且可以处理所有现有的 JSON 内容。
先通过一个例子看看 JSON5 的结构1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26{
foo: '11.1.5,bar'],
while: true,
this: 'is a \
multi-line string',
// this is an inline comment
here: 'is another', // inline comment
/* this is a block comment
that continues on another line */
hex: 0xDEADbeef,
half: .5,
delta: +10,
to: Infinity, // and beyond!
finally: 'a trailing comma',
oh: [
"we shouldn't forget",
'arrays can have',
'trailing commas too',
],
'gulp-jshint': "^2.0.0",
}
由此我们可以来讨论下它与 JSON 格式的区别
key
只要是有效的标识符,则可以不加引号。即使是 ES5 中的保留关键字key-value
都可以使用单引号- 对象和数组尾巴都可跟着逗号
- 字符串可以是多行的,只要加上反斜杠
- 数字可以是十六进制(基数为16)/以小数点开头或结尾/包括Infinity,-Infinity,NaN和-NaN/以明确的加号开始。
- 允许使用注视,单行多行都可以
JSON5 更像 Javascript 对象了,就像开始说的,它更适合人们编写了。但是它并不是 JSON 官方的扩展,所以需要 json5
作为文件扩展名,下面的 package.json5
是现在普遍的写法。
1 | // This file is written in JSON5 syntax, naturally, but npm needs a regular |
使用
Node1
$ yarn add json5
1 | var JSON5 = require('json5'); |
browser1
<script src="json5.js"></script>
转换1
2var obj = JSON5.parse('{unquoted:"key",trailing:"comma",}');
var str = JSON5.stringify(obj);