How to Validate JSON in Nodejs
We can quickly and easily validate our JSON files in Nodejs by calling a free data validation API.
When we make our JSON validation API call, we’ll get a structured response containing multiple lines of useful information about our JSON file — including a succinct report on any errors or warnings present within invalid JSON documents. Here’s a generic API response example in JSON format:
{
"DocumentIsValid": true,
"PasswordProtected": true,
"ErrorCount": 0,
"WarningCount": 0,
"ErrorsAndWarnings": [
{
"Description": "string",
"Path": "string",
"Uri": "string",
"IsError": true
}
]
}
To authorize our API calls, we’ll just need a free Cloudmersive API key, which will allow us to make a limit of 800 API calls per month with no additional commitments.
We can structure our API call using ready-to-run code examples provided below.
First, let’s install the Client SDK with NPM install:
npm install cloudmersive-convert-api-client --save
Or we can just add this snippet to our package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
Now we can call the JSON validation function. We can load our file path in the inputFile
variable:
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.ValidateDocumentApi();
var inputFile = Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer); // File | Input file to perform the operation on.
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.validateDocumentJsonValidation(inputFile, callback);
That’s all there is to it — no more code required! Now we can easily validate our JSON files and get useful information about errors and warnings.