1

I have a doubt when operating with JSON and JS, to obtain max_players. I have the following:

JSON

{
    "football_team" : {
        "real_madrid": {
            "max_players" : 5
        }
    }
}

Javascript

var json = data.toJson();

console.log(json.football_team.real_madrid.max_players)
// return 5

My doubt is if I have a var with the data "real_madrid", how I can get the same result, an example:


var json = data.toJson();
var name_team = "real_madrid";
var max_players = "json.football_team."+name_team+".max_players"

console.log(max_players)
// return json.football_team.real_madrid.max_players

Any suggestions?

Phani Rithvij
  • 4,030
  • 3
  • 25
  • 60
Eduardo
  • 73
  • 1
  • 9

1 Answers1

2

For a JSON object, you need not do json.property.subproperty every time.

Properties can be accessed as json["property"]["subproperty"]

So in your case, you could do json['football_team']['real_madrid']['max_players']

i.e.

var json = data.toJson();
var name_team = "real_madrid";
var max_players = json['football_team'][name_team].max_players;
// or
// var max_players = json['football_team'][name_team]['max_players'];
// or
// var max_players = json.football_team[name_team].max_players;
// or
// var max_players = json.football_team[name_team]['max_players'];

console.log(max_players);

The notations json.property and json['property'] are interchangeable.

And you sometimes need to be careful with the property names.

An example where this fails

json = { "value:" : 4, 'help"': 2, "hello'" : 32, 'data+': 2, "" : '' };

// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json[""]);

// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.);

The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name

And in a JSON when accessing the properties as json['property'] is same as json["property"]

And whenever you have such doubts you can open your browser's console and experiment with the JSON objects.

Phani Rithvij
  • 4,030
  • 3
  • 25
  • 60