0

So I'm having an issue figuring how to reference a variable in JSON dot notation in a meteor application. In doing respJson.userlower.name, userlower is not recognized as a variable. Is there anyway to get around this? The reason I need to have userlower as a variable is because it is being passed into this function and contains the username. And the JSON data that I am getting returns like so:

{"tiandi":{"id":19888066,"name":"Tiandi","profileIconId":7,"summonerLevel":30,"revisionDate":1416925919000}}

try {
        var result = HTTP.get(url, function(err, result){
            console.log(result);
            if (result.statusCode == 200) {
                var userlower = userName.toLowerCase();
                var respJson = JSON.parse(result.content);
                console.log("response received.");
                GameList.insert({
                    IGN: respJson.userlower.name,
                    level: respJson.userlower.summonerlevel,
                    Game: "League of Legends"
                });
            }
        });
    } catch (e) {
        console.log(e);
    }
user2782582
  • 57
  • 1
  • 9
  • There is no such thing as *"JSON dot notation"*. The data you have may be encoded **as** JSON, but once you got it from the server, it will be parsed into a **JavaScript object**. So your question really is: "How to access a property using a variable". – Felix Kling May 29 '15 at 21:38
  • 1
    Oracle seems to disagree: [simple-dot-notation-access-to-json-data](https://docs.oracle.com/database/122/ADJSN/simple-dot-notation-access-to-json-data.htm) – Ray Hulha Aug 30 '17 at 14:50

2 Answers2

2

Bracket notation:

respJson[userlower].summonerlevel,
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • To expand on this, if you want to use a variable to access a JSON object it must be in brackets, otherwise it's going to look for the explicit value (in this case, 'userlower'). – Tony May 29 '15 at 21:00
0

If the key is a constant and if it is a legal JavaScript name and not a reserved word, then a . notation can be used.

If the key doesn't matches above criteria then use [] notation. In the question the key is a variable, so you should go with [] notation.

respJson[userlower].summonerlevel

For more on this Please Refer : JavaScript: The Good parts by Douglas crockford.