前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JSON.parse() 的非严格模式

JSON.parse() 的非严格模式

作者头像
cnguu
发布2020-10-23 16:03:57
1.1K0
发布2020-10-23 16:03:57
举报
文章被收录于专栏:凉风有信凉风有信

# 问题

一个非标准的 JSON 字符串:

代码语言:javascript
复制
// test.json
["a",'b "',"c"]

1 2

使用 JSON.parse() 输出:

代码语言:javascript
复制
'use strict';

const fs = require('fs');

const content = fs.readFileSync('test.json', 'utf8');

console.log(JSON.parse(content)); // SyntaxError: Unexpected token ' in JSON at position 5

1 2 3 4 5 6 7

# 解决方法

代码语言:javascript
复制
'use strict';

const fs = require('fs');

const content = fs.readFileSync('test.json', 'utf8');

console.log(new Function(`return ${ content }`)()); // [ 'a', 'b "', 'c' ]

1 2 3 4 5 6 7

# 总结

封装一个易用函数

代码语言:javascript
复制
function jsonp(source) {
    let jsonObj = null;
    try {
        jsonObj = JSON.parse(source);
    } catch (e) {
        //new Function 的方式,能自动给 key 补全双引号,但是不支持 bigint,所以是下下策
        try {
            jsonObj = new Function(`return ${ source }`)();
        } catch (ee) {
            try {
                jsonObj = new Function(`return '${ source }'`)();
                typeof jsonObj === 'string' && (jsonObj = new Function(`return ${ jsonObj }`)());
            } catch (eee) {
                console.error(eee.message);
            }
        }
    }
    return jsonObj;
}

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020/4/20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # 问题
  • # 解决方法
  • # 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档