小编dae*_*ark的帖子

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

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 " + …
Run Code Online (Sandbox Code Playgroud)

javascript json object-literal

16
推荐指数
2
解决办法
1万
查看次数

标签 统计

javascript ×1

json ×1

object-literal ×1