Alchemist
Alchemist

Reputation: 73

how to implement json file into javascript

i'm trying to implement a local massive data json file into my javascript file i tried this but doesn't work kept return 0

the concept of this function is when i enter the lat and long it should return the grid code associated to them

    function lookupGridcodeByLatAndLong(lat, long)
{
  let gridcode = 0;
$.getJSON('example.json',function( data ) {

  var result = data.find(x => x.lat == lat && x.long == long)
  if (result) { gridcode = result.GRIDCODE;}
});
return gridcode;
};

this is how my data look like

 [{"GRIDCODE":1765,"lat":35.916,"long":-5.401},{"GRIDCODE":1807,"lat":35.907,"long":-5.467},{"GRIDCODE":1798,"lat":35.907,"long":-5.459},{"GRIDCODE":1546,"lat":35.907,"long":-5.409},{"GRIDCODE":1667,"lat":35.907,"long":-5.401},{"GRIDCODE":1729,"lat":35.907,"long":-5.384},{"GRIDCODE":1756,"lat":35.899,"long":-5.484},{"GRIDCODE":1773,"lat":35.899,"long":-5.476},{"GRIDCODE":1828,"lat":35.899,"long":-5.467},{"GRIDCODE":1842,"lat":35.899,"long":-5.459},{"GRIDCODE":1779,"lat":35.899,"long":-5.451},{"GRIDCODE":1728,"lat":35.899,"long":-5.442},{"GRIDCODE":1773,"lat":35.899,"long":-5.434},{"GRIDCODE":1609,"lat":35.899,"long":-5.426}]

Upvotes: 0

Views: 34

Answers (2)

Mukesh Keshu
Mukesh Keshu

Reputation: 467

It's because the getJSON call is asynchronous. You should do Promise based implementation.

Upvotes: 0

Marco
Marco

Reputation: 7277

It's because $.getJSON is running asynchronous.

You need to either use a callback or Promises.

function lookupGridcodeByLatAndLong(lat, long, done) {
  $.getJSON('example.json', function(data) {
    var result = data.find(x => x.lat == lat && x.long == long)

    done(result ? result.GRIDCODE : 0)
  })
}

lookupGridcodeByLatAndLong(lat, long, function(gridcode) {
  // do something with gridcode
})    

Using promises (preferred way)

function lookupGridcodeByLatAndLong(lat, long) {
  return new Promise((resolve, reject) => {
    $.getJSON('example.json', function(data) {
      var result = data.find(x => x.lat == lat && x.long == long)

      if (result) {
        resolve(result.GRIDCODE)
      } else {
        reject()
      }
  })
}

lookupGridcodeByLatAndLong(lat, long)
.then(gridcode => {
  // do something with gridcode
})

Upvotes: 1

Related Questions