使用安全json parser防止json注入

有些程序员若是没有很好的在javascript中解析json数据,每每会直接eval把json转成js对象,这时候若是json的数据中包含了被注入的恶意数据,则可能致使代码注入的问题。javascript


正确的作法是分割出json里包含的特殊字符,而后再解析为对象java


http://json.org/json2.js 中是经过正则来完成的。程序员


// We split the second stage into 4 regexp operations in order to work aroundjson

// crippling inefficiencies in IE's and Safari's regexp engines. First we框架

// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we函数

// replace all simple value tokens with ']' characters. Third, we delete allui

// open brackets that follow a colon or comma or that begin the text. Finally,spa

// we look to see that the remaining characters are only whitespace or ']' orregexp

// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.对象


            if (/^[\],:{}\s]*$/.

test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').

replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').

replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {


// In the third stage we use the eval function to compile the text into a

// JavaScript structure. The '{' operator is subject to a syntactic ambiguity

// in JavaScript: it can begin a block or an object literal. We wrap the text

// in parens to eliminate the ambiguity.


                j = eval('(' + text + ')');

目前很多写的好的框架和js解析函数都取用了这种作法。


因此,之后千万别直接eval了。

相关文章
相关标签/搜索