How to use jsonschema - 10 common examples

To help you get started, we’ve selected a few jsonschema examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github department-of-veterans-affairs / vets-website / test / edu-benefits / 1990e / schema / schema.unit.spec.js View on Github external
describe('1990e schema tests', () => {
  const v = new Validator();
  const files = fs.readdirSync(__dirname);
  files
    .filter(file => file.endsWith('json'))
    .forEach((file) => {
      it(`should validate ${file}`, () => {
        const contents = JSON.parse(fs.readFileSync(path.join(__dirname, file), 'utf8'));
        const submitData = JSON.parse(transform(formConfig, contents)).educationBenefitsClaim.form;
        const result = v.validate(
          JSON.parse(submitData),
          fullSchema1990e
        );
        if (!result.valid) {
          console.log(result.errors); // eslint-disable-line
        }
        expect(result.valid).to.be.true;
      });
github dharmaprotocol / dharma.js / src / schemas / schema_validator.ts View on Github external
public validate(instance: any, schema: Schema): ValidatorResult {
        Validator.prototype.customFormats.BigNumber = function(input) {
            const regex = RegExp("^\\d+(\\.\\d+)?$");
            // This allows undefined inputs, e.g. salt is not present sometimes.
            return input === undefined || (input.isBigNumber && regex.test(input.toString()));
        };

        Validator.prototype.customFormats.wholeBigNumber = function(input) {
            const regex = RegExp("^\\d+$");
            return input && input.isBigNumber && regex.test(input.toString());
        };

        return this._validator.validate(instance, schema);
    }
github dharmaprotocol / dharma.js / src / schemas / schema_validator.ts View on Github external
public validate(instance: any, schema: Schema): ValidatorResult {
        Validator.prototype.customFormats.BigNumber = function(input) {
            const regex = RegExp("^\\d+(\\.\\d+)?$");
            // This allows undefined inputs, e.g. salt is not present sometimes.
            return input === undefined || (input.isBigNumber && regex.test(input.toString()));
        };

        Validator.prototype.customFormats.wholeBigNumber = function(input) {
            const regex = RegExp("^\\d+$");
            return input && input.isBigNumber && regex.test(input.toString());
        };

        return this._validator.validate(instance, schema);
    }
github exratione / cloudformation-deploy / lib / configValidator.js View on Github external
required: true
    },

    progressCheckIntervalInSeconds: {
      type: 'number',
      minimum: 1,
      required: true
    }
  }
});

// --------------------------------------------------------------------------
// Set up the validator.
// --------------------------------------------------------------------------

var validator = new jsonschema.Validator();

/**
 * Since jsonschema doesn't seem to test function types properly at this point
 * in time, hack in an additional test.
 */
validator.attributes.isFunction = function (instance, schema, options, ctx) {
  var result = new jsonschema.ValidatorResult(instance, schema, options, ctx);

  if (!_.isBoolean(schema.isFunction)) {
    return result;
  }

  if (schema.isFunction) {
    if ((instance !== undefined) && (typeof instance !== 'function')) {
      result.addError('Required to be a function.');
    }
github ripple / ripple-lib / src / common / schema-validator.ts View on Github external
require('./schemas/input/prepare-payment-channel-claim.json'),
    require('./schemas/input/prepare-check-create.json'),
    require('./schemas/input/prepare-check-cash.json'),
    require('./schemas/input/prepare-check-cancel.json'),
    require('./schemas/input/compute-ledger-hash.json'),
    require('./schemas/input/sign.json'),
    require('./schemas/input/submit.json'),
    require('./schemas/input/generate-address.json'),
    require('./schemas/input/sign-payment-channel-claim.json'),
    require('./schemas/input/verify-payment-channel-claim.json'),
    require('./schemas/input/combine.json')
  ]
  const titles = schemas.map(schema => schema.title)
  const duplicates = _.keys(_.pickBy(_.countBy(titles), count => count > 1))
  assert.ok(duplicates.length === 0, 'Duplicate schemas for: ' + duplicates)
  const validator = new Validator()
  // Register custom format validators that ignore undefined instances
  // since jsonschema will still call the format validator on a missing
  // (optional)  property

  // This relies on "format": "xAddress" in `x-address.json`!
  validator.customFormats.xAddress = function(instance) {
    if (instance === undefined) {
      return true
    }
    return isValidXAddress(instance)
  }

  // This relies on "format": "classicAddress" in `classic-address.json`!
  validator.customFormats.classicAddress = function(instance) {
    if (instance === undefined) {
      return true
github mrvautin / openKB / routes / api.js View on Github external
router.post('/api/newArticle', (req, res) => {
    const db = req.app.db;
    const lunr_index = req.app.index;
    const v = new Validator();

    // if API is not set or set to false we stop it
    if(typeof config.settings.api_allowed === 'undefined' || config.settings.api_allowed === false){
        res.status(400).json({ result: false, errors: ['Not allowed'] });
        return;
    }

    // if API token is not set or set to an empty value we stop it. Accidently allowing a public API with no token is no 'toke'.
    if(typeof config.settings.api_auth_token === 'undefined' || config.settings.api_auth_token === ''){
        res.status(400).json({ result: false, errors: ['Not allowed'] });
        return;
    }

    // The API schema
    let articleSchema = {
        'type': 'object',
github Casa / Casa-Node-Manager / utils / settingsSchema.js View on Github external
function validateSparseSettingsSchema(data) { // eslint-disable-line id-length

  // json schema cannot handle special characters like emojis. Here we handle length errors.
  if (data.lnd.lndNodeAlias) {
    try {
      utilValidator.isValidAliasLength(data.lnd.lndNodeAlias);
    } catch (error) {
      const response = ALIAS_TOO_LONG_ERROR;
      response.errors[0].instance = data.lnd.lndNodeAlias;

      return response;
    }
  }

  // handle all other errors
  var validator = new Validator();
  validator.addSchema(availableNetworks);
  validator.addSchema(sparseLndSchema);
  validator.addSchema(sparseBitcoindSchema);
  validator.addSchema(availableUnits);
  validator.addSchema(sparseSystemSchema);

  return validator.validate(data, sparseSettingsSchema);
}
github Ingenico-ePayments / connect-sdk-nodejs / products / deviceFingerprint.js View on Github external
var myModule = function (merchantId, paymentProductId, postData, paymentContext, cb) {
  // validate postData
  var isValidRequest = validate(postData, requestSchema);
  if (!isValidRequest.valid) {
    var logger = sdkcontext.getLogger();
    if (sdkcontext.isLoggingEnabled()) {
      logger('error', isValidRequest.errors);
    }
    throw new Error(isValidRequest.errors);
  }
  communicator.json({
    method: 'POST',
    modulePath: '/v1/' + merchantId + '/products/' + paymentProductId + '/deviceFingerprint',
    body: postData,
    paymentContext: paymentContext,
    cb: cb
  });
}
github microsoft / lsif-node / util / src / validate.ts View on Github external
if ((!LSIF.Edge.is11(edge) && !(LSIF.Edge.is1N(edge))) || edge.outV === undefined) {
			// This error was caught before
			return;
		}

		if (edge.label === undefined || !Object.values(LSIF.EdgeLabels).includes(edge.label)) {
			errors.push(new Error(edges[key].element, edge.label ? `requires property "label"` : `unknown label`));
			edges[key].invalidate();
			return;
		}

		let validation: ValidatorResult;
		switch (edge.label) {
			case LSIF.EdgeLabels.item:
				validation = validateSchema(edge, itemSchema);
				break;
			case LSIF.EdgeLabels.contains:
				validation = validateSchema(edge, e1NSchema);
				break;
			default:
				validation = validateSchema(edge, e11Schema);
		}

		const validationErrors: ValidationError[] = validation.errors.filter((error) => error.property === 'instance');
		if (validationErrors.length > 0) {
			edges[key].invalidate();
			errors.push(new Error(edges[key].element, validationErrors.join('; ')));
		}
	});
github OpenEnergyDashboard / OED / src / server / routes / compressedReadings.js View on Github external
function validateMeterBarReadingsParams(params) {
	const validParams = {
		type: 'object',
		maxProperties: 1,
		required: ['meter_ids'],
		properties: {
			meter_ids: {
				type: 'string',
				pattern: '^\\d+(?:,\\d+)*$' // Matches 1 or 1,2 or 1,2,34 (for example)
			}
		}
	};
	const paramsValidationResult = validate(params, validParams);
	return paramsValidationResult.valid;
}