0

Possible Duplicate:
Dynamic object property name

                  $.ajax({
                      url: "ranktonumber.json",
                      dataType: "json",
                      success: function (data) {
                       // my problem is what should be in this line
                      }
                  });

Like you saw , i have jquery (ajax) command that give me json variable . Let's said that I have another variable called "rank" . "rank" is the key of the json . The json is :

{"Recruit":"1",
"Private":"2",
"Private*":"3",
"Private**":"4",
"Private***":"5",
"Corporal":"6",
"Corporal*":"7",
"Corporal**":"8",
"Corporal***":"9"}

how can i use "rank" in json , because that won't work :

data.rank

If you didn't understand yet , here is how i can do it in mirc :

$json(jsonvariable,rankvariable)
Community
  • 1
  • 1
  • possible duplicate of [Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name) and also related to [How to use a variable as a json atribute?](http://stackoverflow.com/questions/4540165/how-to-use-a-variable-as-a-json-atribute). – Felix Kling Sep 08 '12 at 11:13

2 Answers2

2

Use data[rank] instead of data.rank

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Please vote to close the question as well, it's a duplicate. @user1515823: What is the value of `ranke`? Do `console.log(data)` and `console.log(rank)` and have a look wether the key really exists. This might help too: http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-access-a-specific-value – Felix Kling Sep 08 '12 at 11:21
  • Iv'e made new file with [this source](http://pastebin.com/LszuHAQg) and it alert underfinded –  Sep 08 '12 at 11:24
  • @user1515823: You named the variable holding the object `jsonobject`, not `JSON`. `JSON` is a pre-existing global variable and does not have a property `Private`. Try `jsonobject[rank]`. – Felix Kling Sep 08 '12 at 11:27
  • i'm so stupid :) , let me check the page that i ask about him –  Sep 08 '12 at 11:30
  • i have problem in [my page](http://pastebin.com/gjVGFJcr) here is the [console](http://img171.imageshack.us/img171/3011/c8a4eaaadd3b494fb63a179.png) –  Sep 08 '12 at 11:34
  • @user1515823: The file `ranktonumber.json` cannot be found by the server. Make sure the path is correct. This has nothing to do with your question though. – Felix Kling Sep 08 '12 at 11:40
  • i've made function to do it: [click me](http://pastebin.com/i0B7vtt5) but when I document.write(ranktonum("God of War")); it returns me underfinded –  Sep 08 '12 at 11:50
  • slove it thanks to @xdazz and Felix Kling –  Sep 08 '12 at 12:17
0
var thisObj=this;

$.ajax({ 
url: "ranktonumber.json", 
dataType: "json", 
success: function (data) {  
thisObj.data=data;
});

console.log (thisObj.data["rank"])
cube
  • 1,774
  • 4
  • 23
  • 33