I have JSON with references to other parts in that JSON file.
json:
{
"target": "['first']['second']",
"first": {
second: 'hi'
}
}
I want to access that reference from JS. Right now, I execute the following:
// the function I would like to be reviewed
function referenceToObject(json, reference){
return (new Function(
'json', 'return json' + reference
))(json);
}
// json
var example = {
"target": "['first']['second']",
"first": {
second: 'hi'
}
};
// execution
console.log(referenceToObject(example, example.target));
referenceToObject(json, reference){
return (new Function(
'json', 'return json' + reference
))(json);
}
That function basically executes like this:
return json['one']['two'];
I'm not sure if that is completely working, it's part of a larger codebase, but that is the idea.
Is there a better way to extract the JSON
reference? I'm able to change every bit of this code, as well as the JSON
because we are reworking the front- and the backend. So, if you have ideas to improve the JSON
instead of the Javascript
that would also be great.