2

I have a string that carries the path of a nested JSON object:

var path = 'p_Data[0]["BusinessUnit"][0]["BusinessUnit"]' 

How to evaluate the JSON in that path? Right now I use

eval(path)

I know using eval is not good. How to do this without using eval?

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
Okky
  • 10,338
  • 15
  • 75
  • 122
  • 1
    *eval* is only *evil* when it is used unnecessarily as it is slower than other forms of indexing. Given the format of the selector eval seems a reasonable solution. I would actually replace your pathing system if possible instead, but that seems unlikely. – iCollect.it Ltd Aug 16 '13 at 08:48
  • What's the difference to your [previous question](http://stackoverflow.com/questions/18269046/how-to-replace-eval-to-update-value-in-json-when-json-path-is-provided-as-string)? Also, as I commented on another question of yours, there is no such thing a "JSON path" and your question has nothing to do with JSON. – Felix Kling Aug 16 '13 at 08:59
  • @FelixKling I dont wana use eval() – Okky Aug 16 '13 at 09:00
  • @SreekeshOkky: You said the same in the previous question: *"how to replace this use of eval"*. So what is the *difference*? If there is none, please don't ask the same question twice. – Felix Kling Aug 16 '13 at 09:03

1 Answers1

1

You can use DefiantJS (http://defiantjs.com) which extends the global object JSON with the method "search". Using this method you can search your JSON structure with XPath expressions, something like this:

JSON.search( data, '//p_Data[0]/BusinessUnit[0]/BusinessUnit' );

Since there is no example JSON structure, the suggestion above might work. If you post example of your structure, I can provide a JSFiddle version of my suggestion.

To get an idea of how XPath works, check out this XPath Evaluator tool:
http://defiantjs.com/#xpath_evaluator

Hakan Bilgin
  • 1,113
  • 12
  • 11