ryanzec
ryanzec

Reputation: 28030

Proper use of eval in javascript?

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]];
}

Upvotes: 1

Views: 345

Answers (2)

bfavaretto
bfavaretto

Reputation: 71908

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.

Upvotes: 2

Psytronic
Psytronic

Reputation: 6113

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

Upvotes: 0

Related Questions