Dipesh Raichana
Dipesh Raichana

Reputation: 1068

Cannot getting data from external nested json file form jquery

I am trying to get data from external nested json file. this is my ajax call:

 <script>
var json1 = (function () {
  var json1 = null;
  $.ajax({
    'async': false,
    'global': false,
    'url': "PlayerActivity",
    'dataType': "json",
    'success': function (data) {
      json1 = data;
    }
  });
  return json1;
})(); 


var temp1 = [];
$.each(json1,function(i,val){
  player = {};
  player.id = val.id;
  player.Events = val.Events;
  temp1.push(player);
});
  alert(temp1[1].Events); 

  $.each(temp1.Events, function(entryIndex, entry) {
       alert(this.desc); 
    });
</script>

this is my json format:

 var data1=   {
"id": "7",
"Events": [
    {
        "id ": "1",
        "desc": "kjbjhsdbjhbzsdj"
    },
    {
        "id ": "2",
        "desc": "kjbjhsdbjhbzsdj"
    },
    {
        "id ": "3",
        "desc": "kjbjhsdbjhbzsdj"
    }
  ]
}

When i do temp[1].id it shows correctly but when i do temp[1].Events, It shows undefined. I know i didn't define desc but i tried many ways like:

  player.Events.desc = val.desc
  player.desc = val.desc

etc..etc. but nothing worked

Upvotes: 0

Views: 221

Answers (3)

Dipesh Raichana
Dipesh Raichana

Reputation: 1068

just you need to use this

   alert(**player.Events[0].desc**)

instead of

    alert(Events[0].desc)

Upvotes: 0

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38552

Try this way,

player.Events[0].desc

for more: https://www.json.com/json-object

Upvotes: 1

volter9
volter9

Reputation: 735

You're doing it wrong, because AJAX call is asynchronous and you're getting undefined, because data wasn't loaded yet. You can provide a callback to AJAX request, or invoke a function on success. Try this one:

var invokePlayerActivity = function () {
    $.ajax({
        'async': false,
        'global': false,
        'url': "PlayerActivity",
        'dataType': "json",
        'success': function (data) {
            main(data);
        }
    });
}; 

function main (data) {
    var temp1 = [];

    $.each(data, function(i, val){
        player = {};
        player.id = val.id;
        player.Events = val.Events;
        temp1.push(player);
    });

    alert(temp1[1].Events); 

    $.each(temp1.Events, function(entryIndex, entry) {
        alert(this.desc); 
    });
}

invokePlayerActivity();

Upvotes: 0

Related Questions