0

I’m loading a JSON file a reading the values into an array using a for loop

I’m concerned that sometimes the JSON file might become corrupted ie the values Im reading in might become ASCII letters ie 1t3 where the value should of been 123

Is there a test case where you could say if values[a] does not equal a number then set it to “ “ or blank

Thanks, Ben

ben
  • 135
  • 1
  • 1
  • 8
  • 1
    An answer can be found here: https://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric – Kevin Chavez Nov 26 '17 at 02:20
  • 1
    This is not something that you should be concerned with. Detecting and correcting errors is the responsibility of the network layer (ex: TCP, etc.) or the file system. – Derek 朕會功夫 Nov 26 '17 at 02:35

1 Answers1

1

You could use the parseInt() function and check if it returns an integer or NaN. You can check out information on it on W3schools or the MDN Web Docs.

However, in my opinion, it would be better to use regular expressions. If you read the w3schools examples for parseInt(), they show that "0x10" is read as 16.

For a regular expression, try the following:

function isNumber(n) {
  // Added checking for period (in the case of floats)
  var validFloat = function () {
    if (n.match(/[\.][0-9]/) === null || n.match(/[^0-9]/).length !== 1) {
      return false;
    } return true;
      
  };
  return n.match(/[^0-9]/) === null ? true : validFloat();
}

// Example Tests for Code Snippet
console.log(isNumber("993"));
console.log(isNumber("0t1"));
console.log(isNumber("02-0"));
console.log(isNumber("0291"));
console.log(isNumber("0x16"));
console.log(isNumber("8.97"));

The MDN Web Docs have a super helpful page on Regular Expressions.