gpt4 book ai didi

javascript - 使用不带引号的键安全地解析 JSON 字符串

转载 作者:可可西里 更新时间:2023-11-01 01:25:37 26 4
gpt4 key购买 nike

json2.js严格要求所有对象键都用双引号引起来。但是,在 Javascript 语法中,{"foo":"bar"} 等同于 {foo:"bar"}

我有一个文本区域,它接受来自用户的 JSON 输入,并希望“放宽”对双引号键的限制。我已经了解了 json2.js 在评估之前如何分四个阶段验证 JSON 字符串。我能够添加第 5 阶段以允许不带引号的 key ,并且想知道此逻辑是否存在任何安全隐患。

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 );
}

最佳答案

data.replace(/(['"])?([a-zA-Z0-9]+)(['"])?:/g, '"$2":');

这将替换参数名称上的任何单引号,并添加任何丢失的内容。

关于javascript - 使用不带引号的键安全地解析 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4210160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com