schemavalidator.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Schema Validator example
  2. // The example validates JSON text from stdin with a JSON schema specified in the argument.
  3. #include "rapidjson/error/en.h"
  4. #include "rapidjson/filereadstream.h"
  5. #include "rapidjson/schema.h"
  6. #include "rapidjson/stringbuffer.h"
  7. #include "rapidjson/prettywriter.h"
  8. using namespace rapidjson;
  9. int main(int argc, char *argv[]) {
  10. if (argc != 2) {
  11. fprintf(stderr, "Usage: schemavalidator schema.json < input.json\n");
  12. return EXIT_FAILURE;
  13. }
  14. // Read a JSON schema from file into Document
  15. Document d;
  16. char buffer[4096];
  17. {
  18. FILE *fp = fopen(argv[1], "r");
  19. if (!fp) {
  20. printf("Schema file '%s' not found\n", argv[1]);
  21. return -1;
  22. }
  23. FileReadStream fs(fp, buffer, sizeof(buffer));
  24. d.ParseStream(fs);
  25. if (d.HasParseError()) {
  26. fprintf(stderr, "Schema file '%s' is not a valid JSON\n", argv[1]);
  27. fprintf(stderr, "Error(offset %u): %s\n",
  28. static_cast<unsigned>(d.GetErrorOffset()),
  29. GetParseError_En(d.GetParseError()));
  30. fclose(fp);
  31. return EXIT_FAILURE;
  32. }
  33. fclose(fp);
  34. }
  35. // Then convert the Document into SchemaDocument
  36. SchemaDocument sd(d);
  37. // Use reader to parse the JSON in stdin, and forward SAX events to validator
  38. SchemaValidator validator(sd);
  39. Reader reader;
  40. FileReadStream is(stdin, buffer, sizeof(buffer));
  41. if (!reader.Parse(is, validator) && reader.GetParseErrorCode() != kParseErrorTermination) {
  42. // Schema validator error would cause kParseErrorTermination, which will handle it in next step.
  43. fprintf(stderr, "Input is not a valid JSON\n");
  44. fprintf(stderr, "Error(offset %u): %s\n",
  45. static_cast<unsigned>(reader.GetErrorOffset()),
  46. GetParseError_En(reader.GetParseErrorCode()));
  47. }
  48. // Check the validation result
  49. if (validator.IsValid()) {
  50. printf("Input JSON is valid.\n");
  51. return EXIT_SUCCESS;
  52. }
  53. else {
  54. printf("Input JSON is invalid.\n");
  55. StringBuffer sb;
  56. validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
  57. fprintf(stderr, "Invalid schema: %s\n", sb.GetString());
  58. fprintf(stderr, "Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword());
  59. sb.Clear();
  60. validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
  61. fprintf(stderr, "Invalid document: %s\n", sb.GetString());
  62. // Detailed violation report is available as a JSON value
  63. sb.Clear();
  64. PrettyWriter<StringBuffer> w(sb);
  65. validator.GetError().Accept(w);
  66. fprintf(stderr, "Error report:\n%s\n", sb.GetString());
  67. return EXIT_FAILURE;
  68. }
  69. }