var pieces = step.split('.'),
result;
pieces.shift(); //discards superfluous "caso"
result = caso[pieces.shift()];
while (pieces.length >= 1) {
result = result[pieces.shift()];
}
Options to NOT use eval executing JSON string [duplicate]
-
10-10-2022 - |
質問
I want to see which options do I have to execute a string whichs looks for a value inside a JSON without using eval().
My JSON looks like this:
var caso = {
"_id": "C1M3bqsB92i5SPDu",
"type": "bpm",
"bpm": {
"_data": {
"_id_bpm": "bpm_solicitud_viaticos"
},
"milestones": {
"solicitud": {
"toma_de_datos": {
"nombre": "RAUL MEDINA",
"clave": "123",
"departamento": "Finanzas",
"cantidad": "456"
}
}
}
}
}
Now, I'v a string with the value:
var step = "caso.bpm.milestones.solicitud.toma_de_datos.nombre";
I'm getting the value that I want from that JSON with this:
var thevalue = eval(step);
Which are my options instead of eval()? Both efficient and easy to implement?
Thanks a lot for your help!
解決
他のヒント
If the string is always in that format, you could split it and iterate over it
var pieces = step.split('.');
var parent = window;
while(parent && pieces.length) {
parent = parent[pieces.shift()];
}
if(parent && pieces.length === 0) {
// parent is now the value
}
here is a fiddle: http://jsfiddle.net/9ZjEt/
所属していません StackOverflow