任何人都可以解释为什么我放在 MySql 数据库中的字符串变成了一个不可用的对象?我该如何解决?
注意:我正在使用 Nodejs。表项是 (id = VARCHAR and data = BLOB)
JSONf 类似于 JSON,但它也可以用于函数。
item = {"id":"myitem",
"option":[ (function(key){ craftItem(key,{"piece":"armor"},{"item":[]});}),
(function(key){ test2(key);})
]};
str = JSONf.stringify(item); //str = {"id":"myitem","option":["function (key){ craftItem(key,{\"piece\":\"armor\"},{\"item\":[]});}","function (key){ test2(key);}"]}
console.log(typeof str); //string
obj = JSONf.parse(str);
obj.option[1](); //calling the method as expected
//Note: data is blob type in MySql
client.query("INSERT INTO item(id,data) VALUES ('" + item.id + "','" + JSONf.stringify(item) + "')",
function(err, results) { if(err) throw err
client.query("SELECT * FROM item WHERE id='" + item.id + "'" ,function(err, results) {
str = results[0].data;
console.log(str); //<Buffer 7b 22 69 64 22 3a 22 6d 79 69 74 65 6d 22 2c 22 6f 70 74 69 6f 6e 22 3a 5b 22 66 75 6e...
console.log(typeof str); //Object?...
obj = JSONf.parse(str); //ERROR: Unexpected token p
//Note: p is probably from the ' craftItem(key,{\"piece\":\"armor\"} '
obj.option[1](); //never called because program crashed...
});
});
JSONf.stringify = function(obj) {
return JSON.stringify(obj,function(key, value){
return (typeof value === 'function' ) ? value.toString() : value;
});
}
JSONf.parse = function(str) {
return JSON.parse(str,function(key, value){
if(typeof value != 'string') return value;
return ( value.substring(0,8) == 'function') ? eval('('+value+')') : value;
});
}