0

I promise having searched a "simple answer to this" (I insist on the word "Simple"), but unfortunatly I cant find any answer (or approachable answer regarding my understanding of JSON/Jquery). Surely I'm too noob in JSON to create a precise question (and find the right answer...)

Anyway, here my problem.

My JSON file prices.json (example) :

{
  "test1" : {
    "sub_test1_1" : 10,
    "sub_test1_2" : 20,
    "sub_test1_3" : 30,
  },
  "test2" : {
    "sub_test2_1" : 40,
    "sub_test2_2" : 50,
    "sub_test2_3" : 60,
  }
}

Here my jquery

$("#testing").click(function() {
  $.getJSON('/prices.json', function(jsonData) {
    alert(jsonData.test2.sub_test_2_2);
  });
});

The alert give me the right data : 50

So now, I define a simple variable like

var crazyVar = test2;

And I want to put this variable in the string "jsonData.test2.sub_test_2_2" like

$("#testing").click(function() {
  $.getJSON('/prices.json', function(jsonData) {
    alert(jsonData.crazyVar.sub_test_2_2);
  });
});

Of course, it fail :(

I read that I need to play with object, I tried all way to transform crazyVar in a sort of "Object" but impossible to find a just simple solution.

rrk
  • 15,677
  • 4
  • 29
  • 45

1 Answers1

5

While accessing a object key using variable use square [] brackets

var crazyVar = 'test2';
jsonData[crazyVar].sub_test_2_2
brk
  • 48,835
  • 10
  • 56
  • 78
  • Work like a charm, but if I want to extend like var crazyVar_1 = 'test2'; var crazyVar_2 = 'sub_test_2_2'; Can I use ? : jsonData[crazyVar_1].jsonData[crazyVar_2] (don't work actualy) – s.artexess Jan 02 '18 at 18:46