Can anyone help me out with the following. I have 2 JSON files:
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"] } ] }
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); }