0

I have a get method to get the data from a JSON tree:

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";}
}

I would like to set the JSON data using a similar simple method. I expected this to work:

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

But this does not work? Why and what will? The Get works but the Set does not.

  • How do you call the `setJSONNodeData` function ? If `newValue` is a string it has to be quoted. – Titus Nov 01 '19 at 17:59
  • This looks pretty fragile. You can do that without creating a function on the fly. – Felix Kling Nov 01 '19 at 18:05
  • @Felix Kling. For curiosity - I guess this is the fastest method to set the JSON data. If not, what is? and why is it fragile? – Harekrishna Nov 01 '19 at 19:22
  • `eval` (which this basically is) is not necessarily faster than other methods. It's fragile because `path` or `newValue` could contain values that would result in invalid code and thus throw an error, intentionally or unintentionally. It also makes it really awkward to use the function(e.g. string values have to be passed as `"'foo'"` or something). Have a look at [How to set object property (of object property of..) given its string name in JavaScript?](https://stackoverflow.com/q/13719593/218196) – Felix Kling Nov 02 '19 at 04:04

1 Answers1

0

check setJSONNodeData function defined below.

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

In your code, both return are not required and you have to add double quotes for newValue.

Fraddy
  • 331
  • 1
  • 8