JSON模式验证

def*_*ode 26 c c++ json jsonschema

是否有一个稳定的库可以根据模式验证JSON ?

json-schema.org提供了一个实现列表.值得注意的是C和C++缺失.

有没有理由我不能轻易找到C++ JSON模式验证器?
没有其他人想要快速验证传入的JSON文件吗?

Mer*_*ham 18

是否有一个稳定的库可以根据模式验证JSON?

我在谷歌上发现了几个点击:

您还可以将Python或Javascript解释器插入到您的应用程序中,并只运行您已经找到的那些验证器实现的本机版本.

有没有理由我不能轻易找到C++ JSON模式验证器?

我相信JSON起源于Web技术,而C/C++已经不再受Web应用程序实现的青睐.


ans*_*gri 7

Valijson是一个非常好的库,它只依赖于 Boost(我实际上希望改变它)。它甚至不依赖于任何特定的 JSON 解析器,为最常用的库(如 JsonCpp、rapidjson 和 json11)提供适配器。

代码可能看起来很冗长,但您始终可以编写一个帮助程序(JsonCpp 的示例):

#include <json-cpp/json.h>
#include <sstream>
#include <valijson/adapters/jsoncpp_adapter.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/validation_results.hpp>
#include <valijson/validator.hpp>

void validate_json(Json::Value const& root, std::string const& schema_str)
{
  using valijson::Schema;
  using valijson::SchemaParser;
  using valijson::Validator;
  using valijson::ValidationResults;
  using valijson::adapters::JsonCppAdapter;

  Json::Value schema_js;
  {
    Json::Reader reader;
    std::stringstream schema_stream(schema_str);
    if (!reader.parse(schema_stream, schema_js, false))
      throw std::runtime_error("Unable to parse the embedded schema: "
                               + reader.getFormatedErrorMessages());
  }

  JsonCppAdapter doc(root);
  JsonCppAdapter schema_doc(schema_js);

  SchemaParser parser(SchemaParser::kDraft4);
  Schema schema;
  parser.populateSchema(schema_doc, schema);
  Validator validator(schema);
  validator.setStrict(false);
  ValidationResults results;
  if (!validator.validate(doc, &results))
  {
    std::stringstream err_oss;
    err_oss << "Validation failed." << std::endl;
    ValidationResults::Error error;
    int error_num = 1;
    while (results.popError(error))
    {
      std::string context;
      std::vector<std::string>::iterator itr = error.context.begin();
      for (; itr != error.context.end(); itr++)
        context += *itr;

      err_oss << "Error #" << error_num << std::endl
              << "  context: " << context << std::endl
              << "  desc:    " << error.description << std::endl;
      ++error_num;
    }
    throw std::runtime_error(err_oss.str());
  }
}
Run Code Online (Sandbox Code Playgroud)