0

Can anyone help me out with the following. I have 2 JSON files:

  1. names.json: which has all the names age and address array (incase of mulitple residence) of each person. { "people": [ { "name":"Peter Gabriel", "age":42, "address": ["location1","location2","location3"] }, { "name":"Mark Vincent", "age":"25", "address": ["location4","location5"] } ] }

  2. data.json: which has all the address details { "location1": { "country":"Switzerland", "street":"some Avenue", "number": 32 }, "location2": { "country":"Latvia", "street":"some Street", "number": 43 }, "location3": { "country":"Denmark", "street":"some Road", "number": 16 }, "location4": { "country":"Austria", "street":"some Avenue", "number": 54 }, "location5": { "country":"Poland", "street":"some Avenue", "number": 23 } } I need the data.json file data to be in global and loaded before the names.json, but as JSON loading is an asynchronous function how do I do it.

    var jsonAddressData = [];
    function main()
    { 
        loadNamesJSON(function(response) {
            jsonAddressData = JSON.parse(response);
        });
    
    
        loadNamesJSON(function(response) {
            var jsonPeopleData = JSON.parse(response);
            var addressDetail=[];
    
            for(var i in jsonPeopleData.people){
                // ACCESS ADDRESS OBJECT DETAILS HERE
               for(var j in jsonPeopleData.people[i].address){
                   if (jsonPeopleData.people[i].address[j] in jsonAddressData){
    
                       addressDetail.append(jsonAddressData[jsonPeopleData.people[i].address[j]])
                   }
                }
            }
        });
    }
    
    function loadNamesJSON(callback) {
        var request = new XMLHttpRequest();
        request.overrideMimeType("application/json");
        request.open('GET', 'names.json', true); 
    
        request.onreadystatechange = function () {
            if (request.readyState === 4 && request.status ===200) {
                callback(request.responseText);
            }
        };
        request.send(null);
    }
    
    function loadDataJSON(callback) {
        var request = new XMLHttpRequest();
        request.overrideMimeType("application/json");
        request.open('GET', 'data.json', true); 
    
        request.onreadystatechange = function () {
            if (request.readyState === 4 && request.status ===200) {
                callback(request.responseText);
            }
        };
        request.send(null);
    }
    
Deb
  • 157
  • 2
  • 9
  • Can i give you proper example same like this ? – Noman Jul 31 '16 at 10:17
  • sorry didn't get you – Deb Jul 31 '16 at 10:19
  • You can simply call the names.json get function in the success callback of data.json. That will do the trick for you – Rahul Arora Jul 31 '16 at 10:24
  • [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323) this is the same problem, you need the result of an async task to continue with your code – Thomas Jul 31 '16 at 12:29

1 Answers1

1

In Raw JavaScript you could do do this:

function phpEncode(obj){
  var r = [];
  if(obj instanceof Array){
    for(var i=0,l=obj.length; i<l; i++){
      r.push(phpEncode(obj[i]));
    }
    return '%5B'+r.join(',')+'%5D';
  }
  else if(typeof obj === 'object' && obj){
    for(var i in obj){
      if(obj.hasOwnProperty(i)){
        var v = obj[i], s;
        if(typeof v === 'object' && v){
          s = encodeURIComponent('"'+i.replace('"', '\\"')+'":')+phpEncode(v);
        }
        else{
          v = typeof v === 'string' ? '"'+v.replace('"', '\"')+'"' : v;
          s = encodeURIComponent('"'+i.replace('"', '\\"')+'":'+v);
        }
        r.push(s);
      }
    }
    return '%7B'+r.join(',')+'%7D';
  }
  else{
    r = typeof obj === 'string' ? '"'+obj.replace('"', '\\"')+'"' : obj;
    return ''+r;
  }
}
function phpDecode(url){
  return eval('('+decodeURIComponent(url)+')');
}
function post(send, where, success, context){
  var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
  var c = context || this;
  x.open('POST', where); x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  x.onreadystatechange = function(){
    if(x.readyState === 4 && x.status === 200){
      if(success)success.call(c, phpDecode(x.responseText));
    }
  }
  if(typeof send === 'object' && send && !(send instanceof Array)){
    var r = [];
    for(var p in send){
      r.push(encodeURIComponent(p)+'='+phpEncode(send[p]));
    }
    x.send(r.join('&'));
  }
  else{
    throw new Error('send must be an Object');
  }
}
post({}, 'data.json', function(obj1){
  // obj1 holds data.json Object
  post({}, 'names.json', function(obj2){
    // obj2 holds names.json Object
  });
});

Feel free to alter the code above to suit your needs. For instance I'm using a POST request. Of course, it doesn't matter in your case.

If using jQuery:

$.getJSON('data.json', function(obj1){
  // obj1 holds data.json Object
  $.getJSON('names.json', function(obj2){
    // obj2 holds names.json Object
  });
});

The important thing to notice is that AJAX is Asynchronous, so all code that follows must be inside the success function. In other words if you do this:

$.getJSON('data.json', function(obj1){
  var whatever = obj1;
  // obj1 holds data.json Object
  $.getJSON('names.json', function(obj2){
    // obj2 holds names.json Object
  });
});
console.log(whatever);

the console.log(whatever) will return undefined because AJAX has not occurred unless it happened super fast. Anyways, it make take a while for you to fully understand this stuff. Good luck.

StackSlave
  • 10,613
  • 2
  • 18
  • 35