Objects with javascript

Asked

Viewed 42 times

0

How do I access 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 is 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;
});

1 answer

1


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

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

Only it is necessary to remove the comma on line 17, otherwise a parse error will occur.

  • Vlw Marcus. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.