0

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!

Laerion
  • 805
  • 2
  • 13
  • 18
  • you can use: new Function; – Paulo Lima Feb 11 '14 at 19:23
  • Is it just a dot delimited string? – AD7six Feb 11 '14 at 19:25
  • 2
    Try a get from path function see [Javascript: Get deep value from object by passing path to it as string](http://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path-to-it-as-string) or [What is the best to select a javascript object property at any depth?](http://codereview.stackexchange.com/questions/39979/what-is-the-best-to-select-a-javascript-object-property-at-any-depth) – megawac Feb 11 '14 at 19:26
  • @Brad Your comment would actually be helpful if you posted a link explaining the difference. For all we know, the OP completely understands the difference and is simply showing an example of parsed JSON into an object literal that they are working with. – Ian Feb 11 '14 at 19:34
  • @Ian You're right... that's why I added my comment. Either Laerion will know what I'm talking about and explain, or will show where the confusion is, so I can provide a targeted explanation. – Brad Feb 11 '14 at 20:39

2 Answers2

0

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/

Matt Greer
  • 60,826
  • 17
  • 123
  • 123
0
var pieces = step.split('.'),
    result;

pieces.shift(); //discards superfluous "caso"
result = caso[pieces.shift()];

while (pieces.length >= 1) {
    result = result[pieces.shift()];
}
Dexygen
  • 12,287
  • 13
  • 80
  • 147