学习JSON5,从这里开始!

910 阅读1分钟
一、JSON5 解决了什么问题?

JSON5 对 JSON 进行了扩展,增加了如下功能:

  • 可以增加单行或多行注释;
  • 去掉 JSON序列化后,key的双引号,减少 JSON 文件大小;
  • object 和 array 用 逗号结尾,不会视为语法错误;
  • 序列化后的 string 可以用单引号和双引号,JSON中只能用双引号;
  • number 增加了16进制、小数、正负等;
  • JSON 介绍及用法,看这里!

二、怎么使用?

使用 Node.js 环境,通过一个简单示例,展示JSON5的使用方式以及新的功能。Node.js的安装,看这里!

  1. 新建文件夹 learn-json5;
  2. 安装 json5
cd learn-json5
npm install json5
  1. 新建 test.js 文件,并复制下面代码到文件中,保存。
const JSON5 = require('json5')

const obj = {
    // comments
    /* 
        multi 
        comments
    */
    unquoted: 'and you can quote me on that',
    singleQuotes: 'I can use "double quotes" here',
    lineBreaks: "Look, Mom! \
  No \\n's!",
    hexadecimal: 0xdecaf,
    leadingDecimalPoint: .8675309, andTrailing: 8675309.,
    positiveSign: +1,
    trailingComma: 'in objects', andIn: ['arrays',],
    "backwardsCompatible": "with JSON",
}
const res = JSON5.stringify(obj)

console.log(res)
console.log("***************************");
console.log(JSON5.parse(res))

/* 输出结果如下:

{unquoted:'and you can quote me on that',singleQuotes:'I can use "double quotes" here',lineBreaks:"Look, Mom!   No \\n's!",hexadecimal:912559,leadingDecimalPoint:0.8675309,andTrailing:8675309,positiveSign:1,trailingComma:'in objects',andIn:['arrays'],backwardsCompatible:'with JSON'}
***************************
{
  unquoted: 'and you can quote me on that',
  singleQuotes: 'I can use "double quotes" here',
  lineBreaks: "Look, Mom!   No \\n's!",
  hexadecimal: 912559,
  leadingDecimalPoint: 0.8675309,
  andTrailing: 8675309,
  positiveSign: 1,
  trailingComma: 'in objects',
  andIn: [ 'arrays' ],
  backwardsCompatible: 'with JSON'
}

*/
  1. 运行
node test.js

三、参考文档