有没有一种方法可以使用新的Function设置JSON字段



我有一个从JSON树中获取数据的get方法:

var tree = { user: [{ name: 'name1', email:'email1' }, {name: 'name2', email:'email2'}] };
getJSONNodeData(tree, 'user[1].name');
function getJSONNodeData(root, path) {
try {
return (new Function('root', 'return root.' + path + ';'))(root);
} catch (e) {return "JSON Error";}
}

我想使用类似的简单方法设置JSON数据。我本以为这会奏效:

function setJSONNodeData(root, path, newValue) {
return (new Function('root', 'return root.' + path + '=' + newValue +';'))(root);
}

但这不管用吗?为什么以及会发生什么?Get有效,但Set无效。

检查下面定义的setJSONNodeData函数。

function setJSONNodeData(root, path, newValue) {
try {
(new Function('root', 'root.' + path + '="' + newValue + '";'))(root);
} catch (e) {return "JSON Error";}
}

在您的代码中,两个return都不是必需的,并且您必须为newValue添加双引号。

最新更新