项目作者: yusufnb

项目描述 :
verify-json
高级语言: JavaScript
项目地址: git://github.com/yusufnb/verify-json.git
创建时间: 2020-04-15T04:14:05Z
项目社区:https://github.com/yusufnb/verify-json

开源协议:MIT License

下载


Verify JSON

Library to verify JSON structure easily using a lightweight JSON schema syntax

About

This project results from my need to verify JSON schema in a lightweight manner, without the need for an extensive definition and development code.

The schema syntax is minimalist and extremely easy to write.

Installation

  1. npm install -s verify-json
  2. const verify = require('verify-json')
  3. import verify from 'verify-json';

Example

  1. const { verify } = require("verify-json");
  2. let json = {
  3. markers: [
  4. {
  5. stars: 5,
  6. name: 'Rixos The Palm Dubai',
  7. location: [25.1212, 55.1535],
  8. favorite: true,
  9. color: 'red',
  10. },
  11. {
  12. stars: 4,
  13. name: 'Shangri-La Hotel',
  14. location: [25.2084, 55.2719],
  15. color: 'blue',
  16. },
  17. ],
  18. };
  19. // <key>:<validator>
  20. // <key>:?<validator> - uses ? for optional
  21. // <key> - required non null attribute of any type
  22. // Skip all the quotations
  23. const schema = `{markers: [{
  24. stars:i,
  25. name:string,
  26. location:[:lat,:long],
  27. favorite:?b,
  28. color:color
  29. }]
  30. }`;
  31. // customValidators are optional. See built-in validators.
  32. const customValidators = {
  33. lat: (val) => val >= -90 && val <= 90,
  34. long: (val) => val >= -180 && val <= 180,
  35. color: (val, args) => {
  36. // demonstrating conditional validations. args = { json, path, parent }
  37. return (args.parent.stars === 5 && val === 'red') || (args.parent.stars === 4 && val === 'blue');
  38. },
  39. };
  40. let result = verify(json, schema, customValidators);
  41. console.log(result); // true
  42. json.markers[0].location[0] = 1000;
  43. json.markers[0].color = 'blue';
  44. try {
  45. verify(json, schema, customValidators);
  46. } catch (error) {
  47. console.log('error', error); // json.markers.0.location.0: validation failed, json.markers.0.color: validation failed
  48. }

Built-in Validators

Following validators are built in and can be used directly -

  1. {
  2. string : _.isString,
  3. s : _.isString, // alias for string
  4. number : _.isNumber,
  5. n : _.isNumber, // alias for number
  6. boolean : _.isBoolean,
  7. b : _.isBoolean, // alias for boolean
  8. integer : _.isInteger,
  9. i : _.isInteger, // alias for integer
  10. }

Use as a mixin

Since lodash is a dependency, this method is also exposed as a lodash mixin. Once imported anywhere, you can simply use _.verify to access it.

  1. _.verify(json, schema, customValidators)

License

MIT © Yusuf Bhabhrawala