Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Created December 29, 2021 18:47
Show Gist options
  • Save mitchallen/d19a4103cb2b107eba6752acfd770abb to your computer and use it in GitHub Desktop.
Save mitchallen/d19a4103cb2b107eba6752acfd770abb to your computer and use it in GitHub Desktop.
JSON parser and validator
// Author: Mitch Allen
// File: parser.js
import { readFileSync } from 'fs';
import Ajv from 'ajv';
const ajv = new Ajv();
export function parser( inputFile, schemaFile ) {
function readJsonFile(file) {
let raw = readFileSync(file);
return JSON.parse(raw);
}
let input = readJsonFile(inputFile);
let schema = readJsonFile(schemaFile);
const isValid = ajv.validate(schema, input);
if (!isValid) {
console.error(JSON.stringify(ajv.errors, null, 2));
return undefined;
}
console.info('[INFO] Valid!');
return input;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment