json2.js严格要求所有对象键都被双引号引起来。但是,在 Javascript 语法{"foo":"bar"}
中等价于{foo:"bar"}
.
我有一个 textarea 接受来自用户的 JSON 输入,并希望“放宽”对双引号键的限制。我已经了解了 json2.js 如何在对 JSON 字符串进行评估之前分四个阶段对其进行验证。我能够添加第 5 阶段以允许未引用的密钥,并且想知道此逻辑是否存在任何安全隐患。
var data = '{name:"hello", age:"23"}';
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, ":") // EDITED: allow key:[array] by replacing with safe char ":"
/** everything up to this point is json2.js **/
/** this is the 5th stage where it accepts unquoted keys **/
.replace(/\w+\s*\:/g, ":")) ) { // EDITED: allow any alphanumeric key
console.log( (new Function("return " + data))() );
}
else {
throw( "Invalid JSON: " + data );
}