首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >学习JSON5,从这里开始!

学习JSON5,从这里开始!

原创
作者头像
Learn-anything.cn
发布2021-12-07 20:11:52
6680
发布2021-12-07 20:11:52
举报
文章被收录于专栏:learn-anything.cnlearn-anything.cn
一、JSON5 解决了什么问题?

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

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

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

  • 新建文件夹 learn-json5;
  • 安装 json5
cd learn-json5
npm install json5
  • 新建 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'
}

*/
  • 运行
node test.js
三、参考文档

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、JSON5 解决了什么问题?
  • 二、怎么使用?
  • 三、参考文档
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档