Generate JSON schema from JSON files.
Used to create validation files to check live data.
import { JsonClient } from '@reuters-graphics/graphics-bin';
const json = new JsonClient();
const schema = json.makeSchema({ some: 'data' });
Data to make JSON schema to validate
Generate JSON schema from JSON files.
Used to create validation files to check live data.
import { JsonClient } from '@reuters-graphics/graphics-bin';
const json = new JsonClient();
await json.makeSchemaFile('myData.json', 'myData.schema.json');
graphics json:make-schema config.json schema.json
Description
Make a JSON schema from an existing JSON file
Usage
$ graphics json:make-schema <src> <dest> [options]
Options
-h, --help Displays this message
Path to data file to make JSON schema from
Path to schema file
Validate data using AJV and JSON schema
import { JsonClient } from '@reuters-graphics/graphics-bin';
import type { JSONSchemaType } from 'ajv';
const json = new JsonClient();
// Data to validate
const data = { name: 'Jon', age: 40 };
// Define a JSON schema
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'age'],
additionalProperties: false
} as JSONSchemaType<typeof data>;
// Validate data
const [isValid, errors] = json.validateData(schema, data);
JSON schema
Data to validate
An array where the first item is boolean and the second is an array of AJV error objects.
Generate a JSON schema for some data as a snapshot and then validate the data with it on subsequent runs.
import { JsonClient } from '@reuters-graphics/graphics-bin';
import path from 'path';
const json = new JsonClient();
// Data to validate
const data = { name: 'Jon', age: 40 };
// Path to your snapshot file
const snapshot = path.join(process.cwd(), '.snapshots/myData.json');
// Validate data
const [isValid, errors] = json.validateDataWithSnapshot(
data,
snapshot
);
Data to validate
Path to save JSON schema snapshot to
Update the snapshot
Format errors into a loggable string.
import { JsonClient } from '@reuters-graphics/graphics-bin';
const json = new JsonClient();
// ...
const [isValid, errors] = json.validateData(schema, data);
if (!isValid) {
// Format errors into a string
const errorMessage = json.formatValidationErrors(errors);
console.log(errorMessage); // "/name must be string, /age must be number"
}
Array of error objects returned from JsonClient.validateData
Formatted error string
JSON client for validating data with JSON schema.