schemavalidator.cpp 2.5 KB

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