rapidjson Schema 文档多根错误

rapidjson Schema Document multiple roots error

我正在使用 RapidJSON 来解析 JSON 文件。我正在尝试使用 rapidjson::SchemaDocument 制作 JSON 模式来验证收到的 JSON 文件。

但是,当我尝试构建由网站 liquid-technologies.com 生成的架构文档时,收到“错误代码 2”,这表明我正在尝试的 JSON(架构)文档to parse 有多个根,即使它只有一个。

这是我要解析的架构文档:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "title": {
      "type": "string"
    },
    "pay": {
      "type": "number"
    },
    "country": {
      "type": "string"
    },
    "employer": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "workforce": {
          "type": "integer"
        },
        "officelocation": {
          "type": "string"
        }
      },
      "required": [
        "name",
        "workforce",
        "officelocation"
      ]
    },
    "location": {
      "type": "string"
    },
    "flexibleHours": {
      "type": "boolean"
    },
    "description": {
      "type": "string"
    }
  },
  "required": [
    "title",
    "pay",
    "country",
    "employer",
    "location",
    "flexibleHours",
    "description"
  ]
}

这是我的代码:

std::string schemaJson = readFile("../jsonschemas/postjobschema.json");
    rapidjson::Document sd;
    if (sd.Parse(schemaJson.c_str()).HasParseError()) {
        std::cout << "Schema has parse errors" << std::endl;
        if (sd.GetParseError() == rapidjson::kParseErrorDocumentRootNotSingular)
            std::cout << "There are multiple roots" << std::endl;
    }

是我的架构不正确,还是我做错了什么?

我认为你的架构是正确的,但你的代码有问题。

我用 rapidjson 的 example/schemavalidator 测试了你的 schema json 和模拟输入 json,结果一切正常。

input.json:

{
    "title": "foo",
    "pay": 100,
    "country": "US",
    "employer": { "name": "bar", "workforce": 12, "officelocation": "UK"},
    "location": "CA",
    "flexibleHours": true,
    "description": "hello"
}
./bin/schemavalidator /tmp/schema.json < /tmp/input.json

Input JSON is valid.

您想用 rapidjson::FileReadStream 阅读您的架构 json 文件吗?

    // Read a JSON schema from file into Document
    Document d;
    char buffer[4096];

    {
        FILE *fp = fopen(argv[1], "r");
        if (!fp) {
            printf("Schema file '%s' not found\n", argv[1]);
            return -1;
        }
        FileReadStream fs(fp, buffer, sizeof(buffer));
        d.ParseStream(fs);
        if (d.HasParseError()) {
            fprintf(stderr, "Schema file '%s' is not a valid JSON\n", argv[1]);
            fprintf(stderr, "Error(offset %u): %s\n",
                static_cast<unsigned>(d.GetErrorOffset()),
                GetParseError_En(d.GetParseError()));
            fclose(fp);
            return EXIT_FAILURE;
        }
        fclose(fp);
    }