JSON.parse() 的非严格模式

时间:2022-07-28
本文章向大家介绍JSON.parse() 的非严格模式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

# 问题

一个非标准的 JSON 字符串:

// test.json
["a",'b "',"c"]

1 2

使用 JSON.parse() 输出:

'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

# 解决方法

'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

# 总结

封装一个易用函数

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