]>
git.proxmox.com Git - ceph.git/blob - ceph/src/rapidjson/example/schemavalidator/schemavalidator.cpp
1 // Schema Validator example
3 // The example validates JSON text from stdin with a JSON schema specified in the argument.
5 #include "rapidjson/error/en.h"
6 #include "rapidjson/filereadstream.h"
7 #include "rapidjson/schema.h"
8 #include "rapidjson/stringbuffer.h"
10 using namespace rapidjson
;
12 int main(int argc
, char *argv
[]) {
14 fprintf(stderr
, "Usage: schemavalidator schema.json < input.json\n");
18 // Read a JSON schema from file into Document
23 FILE *fp
= fopen(argv
[1], "r");
25 printf("Schema file '%s' not found\n", argv
[1]);
28 FileReadStream
fs(fp
, buffer
, sizeof(buffer
));
30 if (d
.HasParseError()) {
31 fprintf(stderr
, "Schema file '%s' is not a valid JSON\n", argv
[1]);
32 fprintf(stderr
, "Error(offset %u): %s\n",
33 static_cast<unsigned>(d
.GetErrorOffset()),
34 GetParseError_En(d
.GetParseError()));
41 // Then convert the Document into SchemaDocument
44 // Use reader to parse the JSON in stdin, and forward SAX events to validator
45 SchemaValidator
validator(sd
);
47 FileReadStream
is(stdin
, buffer
, sizeof(buffer
));
48 if (!reader
.Parse(is
, validator
) && reader
.GetParseErrorCode() != kParseErrorTermination
) {
49 // Schema validator error would cause kParseErrorTermination, which will handle it in next step.
50 fprintf(stderr
, "Input is not a valid JSON\n");
51 fprintf(stderr
, "Error(offset %u): %s\n",
52 static_cast<unsigned>(reader
.GetErrorOffset()),
53 GetParseError_En(reader
.GetParseErrorCode()));
56 // Check the validation result
57 if (validator
.IsValid()) {
58 printf("Input JSON is valid.\n");
62 printf("Input JSON is invalid.\n");
64 validator
.GetInvalidSchemaPointer().StringifyUriFragment(sb
);
65 fprintf(stderr
, "Invalid schema: %s\n", sb
.GetString());
66 fprintf(stderr
, "Invalid keyword: %s\n", validator
.GetInvalidSchemaKeyword());
68 validator
.GetInvalidDocumentPointer().StringifyUriFragment(sb
);
69 fprintf(stderr
, "Invalid document: %s\n", sb
.GetString());