使用不带引号的键安全地解析JSON字符串 [英] Safely parsing a JSON string with unquoted keys
问题描述
json2.js 严格要求所有对象密钥都是双引号。但是,在Javascript语法 {foo:bar}
相当于 {foo:bar}
。
json2.js is strict requiring all object keys be double-quoted. However, in Javascript syntax {"foo":"bar"}
is equivalent to {foo:"bar"}
.
我有一个textarea接受来自用户的JSON输入,并希望轻松双重引用键的限制。我已经看过json2.js如何在它出现之前的四个阶段验证JSON字符串。我能够添加第5个阶段以允许不带引号的密钥,并想知道这个逻辑是否有任何安全隐患。
I have a textarea that accepts JSON input from the user and would like to "ease" the restriction on double quoting the keys. I've looked at how json2.js validates a JSON string in four stages before it evals it. I was able to add a 5th stage to allow unquoted keys and would like to know if there are any security implications to this logic.
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":');
这将替换参数名称上的任何单引号,并添加任何缺少的引号。
That will replace any single quotes on the parameter name, and add any that are missing.
这篇关于使用不带引号的键安全地解析JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!