Advertisement
Guest User

Untitled

a guest
Apr 30th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. #define PICOJSON_USE_INT64
  2. #include <fstream>
  3. #include <iostream>
  4. #include <stdexcept>
  5.  
  6. #include <picojson.h>
  7.  
  8. #include <valijson/utils/picojson_utils.hpp>
  9. #include <valijson/adapters/picojson_adapter.hpp>
  10. #include <valijson/schema.hpp>
  11. #include <valijson/schema_parser.hpp>
  12. #include <valijson/validation_results.hpp>
  13. #include <valijson/validator.hpp>
  14.  
  15. using std::cerr;
  16. using std::endl;
  17.  
  18. using valijson::Schema;
  19. using valijson::SchemaParser;
  20. using valijson::Validator;
  21. using valijson::ValidationResults;
  22. using valijson::adapters::PicoJsonAdapter;
  23.  
  24. int json(int argc, char *argv[])
  25. {
  26. if (argc != 3) {
  27. cerr << "Usage: " << argv[0] << " <schema document> <test/target document>" << endl;
  28. return 1;
  29. }
  30.  
  31. //Load the document containing the schema
  32. picojson::value schemaDocument;
  33. if (!valijson::utils::loadDocument(argv[1], schemaDocument)) {
  34. cerr << "Failed to load schema document." << endl;
  35. return 1;
  36. }
  37.  
  38.  
  39. // Load the document that is to be validated
  40. picojson::value targetDocument;
  41. if (!valijson::utils::loadDocument(argv[2], targetDocument)) {
  42. cerr << "Failed to load target document." << endl;
  43. return 1;
  44. }
  45.  
  46. // Parse the json schema into an internal schema format
  47. Schema schema;
  48. SchemaParser parser;
  49. PicoJsonAdapter schemaDocumentAdapter(schemaDocument);
  50. try {
  51. parser.populateSchema(schemaDocumentAdapter, schema);
  52. }
  53. catch (std::exception &e) {
  54. cerr << "Failed to parse schema: " << e.what() << endl;
  55. return 1;
  56. }
  57.  
  58. // Perform validation
  59. Validator validator(Validator::kWeakTypes);
  60. ValidationResults results;
  61. PicoJsonAdapter targetDocumentAdapter(targetDocument);
  62. if (!validator.validate(schema, targetDocumentAdapter, &results)) {
  63. std::cerr << "Validation failed." << endl;
  64. ValidationResults::Error error;
  65. unsigned int errorNum = 1;
  66. while (results.popError(error)) {
  67.  
  68. std::string context;
  69. std::vector<std::string>::iterator itr = error.context.begin();
  70. for (; itr != error.context.end(); itr++) {
  71. context += *itr;
  72. }
  73.  
  74. cerr << "Error #" << errorNum << std::endl
  75. << " context: " << context << endl
  76. << " desc: " << error.description << endl;
  77. ++errorNum;
  78. }
  79. return 1;
  80. }
  81.  
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement