Objects with javascript

0

How do I access the data from this Json file. For example return the name:

{
  "potions": {
    "1": {
      "id": 1,
      "name": "Aging Potion",
      "image": "aging-potion.png",
      "price": 29.99,
      "effect": "Causes the drinker to advance in age",
      "ingredients": [
        "Red Wine",
        "Prune Juice",
        "Hairy Fungus",
        "Tortoise Shell",
        "Caterpillar",
        "Bat Tongue"
      ]
    },
  }
}
  

My Ajax looks like this:

var get = function(url, callback){
    var teste = new XMLHttpRequest();
    teste.onreadystatechange = function(){
        if(teste.readyState == 4){
                callback(teste.responseText, teste.status);
        }
    };
        teste.open('Get', 'potions.json', true);
        teste.send(get);
};

get('potions.json', function(data){ 
    document.getElementById('pteste').innerHTML = data.potions['1'].name;
});
    
asked by anonymous 10.04.2018 / 23:13

1 answer

1

You need to convert the string to json format for a valid object before attempting to use it:

var obj = JSON.parse(data);
document.getElementById('pteste').innerHTML = obj.potions['1'].name;

It is only necessary to remove the comma in line 17, otherwise a parse error will occur.

    
11.04.2018 / 00:10