JSON.parse () 的非严格模式

问题

一个非标准的 JSON 字符串:

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

使用 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

解决方法

'use strict';

const fs = require('fs');

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

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

总结

封装一个易用函数

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;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!