I know that eval
is bad and all but I can't really find any better way of doing this.
I receive an input string (from a command prompt) and I need to modify some value of a nested item inside a stored JSON object representing a file system.
Here it is in more detail:
I am making an edit
command for my command prompt, and its form is like this:
edit <filename>
My code receives <filename>
and looks in a file system for it, to check its existence.
Here is an example file system (in JSON, Linux based):
{
"home": {
"default": {
"documents": {},
"tst": "This is a file"
}
}
"etc": {}
"tmp": {}
}
So if the user's PWD (present working directory) is /home
, and they enter default/tst
, they should be editing /home/default/tst
.
This is how I tried:
var wdir=JSON.parse(localStorage.getItem("filesys")); // Whole dir (wdir) - Obtain the stored file system
var cdir=wdir; // Current dir (cdir)
var i; // loop var
var l=f.length; // f is something like ["default","tst"]
var runstr="wdir"; // The thing to eval
for(i=0;i<l-1;i++){ // Go through everything except the last (the last is the file)
if(f[i] in cdir){ // If it exists in the current dir
cdir=cdir[f[i]]; // Go into a directory and modify cdir, not wdir
runstr+="['"+f[i]+"']"; // Add more to runstr
}
}
cdir[n]=t.value; // t.value is the new file content
eval(runstr+'=cdir;'); // run runstr to modify value
localStorage.setItem("filesys",JSON.stringify(wdir)); // Save the file system
Side note: this works, I'm just looking for a better solution
I've heard that eval
is 'evil' and also slow as the JS interpreter has to start again. Since I'm using it for such a simple task I thought that there must be another way.
What better way can I set the value of a key that could be nested inside objects inside objects?
If you need any more information, you can ask in the comments and I will add it to my question.