1

So I have this json object where the structure is variable depending on how you retrieve the data. Lets say the object looks like this in one case:

{
  "status": "success",
  "data": {
    "users": [...]
  }
}

but looks like this in another case:

{
  "status": "success",
  "data": {
    "posts": [...]
  }
}

Now for the first example, they way I am dynamically getting the data is like this:

var dataLocation = 'data.users';
var responseData;
eval('responseData = response.' +dataLocation + ';');

This allow me to configuration it. Just note that this is just a simple example, in the real code there is only one function to parse the data and I would be passed dataLocation in as a parameter.

Now my first question is whether or not there is a better want to accomplish the same goal without using eval?

If not, the second question is what do I need to do to the eval statement to make sure it is safe (dataLocation should never be passed in from a user, it will always come from code but still).

UPDATE

Based on the comment from Bergi, I am now using this:

var parts = dataListLocation.split('.');

for(var x = 0; x < parts.length; x += 1) {
  responseData = responseData[parts[x]];
}
ryanzec
  • 27,284
  • 38
  • 112
  • 169
  • exact duplicate of [is it evil to use eval to convert a string to a function?](http://stackoverflow.com/questions/14396647/is-it-evil-to-use-eval-to-convert-a-string-to-a-function) – Bergi Apr 23 '13 at 14:23
  • 1
    See [thousand ways to do this better](http://stackoverflow.com/a/14397052/1048572) – Bergi Apr 23 '13 at 14:24

2 Answers2

2

You should use bracket notation instead of eval:

var responseData = response['data']['users'];

Note: from your description, what you have is a JavaScript object literal. A JSON would be that same object encoded as a string (with JSON.stringify, for example). There is no such thing as a "JSON object", you either have a JavaScript object, or a JSON string.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

You can use key indexers for objects in JS:

var responseData response.data['users]';

That is after getting rid of the data. in our dataLocation

Psytronic
  • 6,043
  • 5
  • 37
  • 56