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

2 に答える 2

2

の代わりにブラケット表記を使用する必要がありますeval

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

注:あなたの説明から、あなたが持っているのはJavaScriptオブジェクトリテラルです。JSON は、文字列としてエンコードされた同じオブジェクトです (JSON.stringifyたとえば、 を使用)。「JSON オブジェクト」のようなものはありません。JavaScript オブジェクトまたは JSON 文字列のいずれかがあります。

于 2013-04-23T14:17:02.003 に答える
0

JS のオブジェクトにキー インデクサーを使用できます。

var responseData response.data['users]';

それはdata.、dataLocationの を削除した後です。

于 2013-04-23T14:17:36.170 に答える