Rule Definition
JSON.parse and JSON.stringify methods are used to analyse JSON data. Since JSON data often comes from external sources (such as from a web service callback), there is a risk that this data is poorly formatted which would lead to an error and unexpected behavior unless the JSON.parse and JSON.stringify are within a try/catch block handling the error.
Remediation
Always use JSON.parse in try/catch block
Violation Code Sample
function readJSON(filePath, callback) {
fs.readFile(filePath, (err, data) => {
var parsedJson;
// Handle error
if (err) {
return callback(err);
}
// Parse JSON
parsedJson = JSON.parse(data);
return (parsedJson !== 'undefined');
});
}
Fixed Code Sample
function readJSON(filePath, callback) {
fs.readFile(filePath, (err, data) => {
var parsedJson;
// Handle error
if (err) {
return callback(err);
}
// Parse JSON
try {
parsedJson = JSON.parse(data);
} catch (exception) {
return callback(exception);
}
// Everything is ok
return callback(null, parsedJson);
});
}
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse
Related Technologies
Technical Criterion
CWE-390 - Detection of Error Condition Without Action
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.