Created
October 21, 2014 13:16
-
-
Save magicdawn/b9ea7b05c92913da439d to your computer and use it in GitHub Desktop.
JSON._parse not quoted key string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = parse | |
function parse(s) { | |
s = s.replace(/'/g, "\'") | |
.replace(/"/g, '\"') | |
.replace(/\n/g, '\\n') | |
.replace(/\r/, '\\r') | |
var code = "return " + s | |
var f = new Function(code) | |
return f() | |
} | |
var s = '{ "name": "zhang" }' | |
var ss = '{ name: "zhang" }' | |
console.log(parse(s)); | |
console.log(parse(ss)); | |
var o = parse(ss) | |
console.log(o.name); | |
/* | |
{ name: 'zhang' } | |
{ name: 'zhang' } | |
zhang | |
*/ |
可能执行恶意代码...放在vm的sandbox里执行...
module.exports = parse
var vm = require('vm');
function parse (s) {
var code = "var json = " + s;
var ctx = {}
vm.runInNewContext(code,ctx) // try catch 一下
return ctx.json
}
var s = '{ name: "zhang" }'
var attack = ' global.name = "zhang"; require("fs"); json = { name: "zhang" }'
// 攻击测试
parse(s)
// parse(attack) // global is undefined
// 速度测试
console.time('vm 模块')
for (var i = 0; i < 10000; i++) {
parse(s)
};
console.timeEnd('vm 模块')
var fJSON = require('fbbk-json');
console.time('fJSON 模块')
for (var i = 0; i < 10000; i++) {
fJSON.parse(s)
};
console.timeEnd('fJSON 模块')
/*
vm 模块: 9917ms
fJSON 模块: 30ms
关于vm模块 CPU 2.3 GHz
1. 4K ms
sandbox = {}
runInNewContext(code,sandbox)
2. 6K ms
ctx = createContext()
runInContext(code,ctx)
9K ms 是 既newContext 又 runInNewContext , 写错了
**/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
对new Function 里的字符串处理有阴影...我那个replace啥都没干