1

i need to access a json file dynamically and am using the following code. In this case, 'bpicsel' and 'temp' are variables. The end result would be something like 'data[0].extit1'

var title="data["+bpicsel+"].extit"+temp;
$.getJSON('labs.json', function(data){
    title2 = eval(title);
    });

this works - but i am often told not to use eval - is there a better way?

drkoss
  • 79
  • 1
  • 6
  • `var title=data.bpicsel["extit" + temp];` inside of the getJSON call – megawac Nov 19 '13 at 02:22
  • 2
    There's always another way besides `eval` – tymeJV Nov 19 '13 at 02:22
  • @megawac thanks for the reply. that doesn't seem to work - it creates the string i need but isn't evaluated in the function - it doesn't pull the entry from the json file that i need to access. For example, it produces data[0].extit1 instead of giving me the value at that location. – drkoss Nov 19 '13 at 02:24

1 Answers1

1

This should work just fine

var title = data[bpicsel]['extit'+temp];

Now get your data as follows:

$.getJSON('labs.json', function(data){ var title = data[bpicsel]['extit'+temp]; //no need for eval here });

benathon
  • 7,455
  • 2
  • 41
  • 70
  • 1
    thanks for the reply, but same as the megawac answer, that doesn't seem to work - it creates the string i need but isn't evaluated in the function - it doesn't pull the entry from the json file that i need to access. For example, it produces data[0].extit1 instead of giving me the value at that location. – drkoss Nov 19 '13 at 02:27
  • sorry I realized that you should use `title2 = data[bpicsel]['extit'+temp]`. does that help? This may help you as well: http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name – benathon Nov 19 '13 at 02:36
  • 1
    thanks! that worked. for some reason, using var title = blahblah didn't work - maybe scope? – drkoss Nov 19 '13 at 02:40
  • Yes, scope would cause that issue. Also the data variable isn't available until getJSON is done getting it, and passing into your anonymous function – benathon Nov 19 '13 at 02:44