JSON 模式验证

发布于 2024-10-11 21:55:54 字数 419 浏览 2 评论 0原文

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

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

我无法轻松找到 C++ JSON 模式验证器是否有原因?
难道没有其他人想要一种快速的方法来验证传入的 JSON 文件吗?

Is there a stable library that can validate JSON against a schema?

json-schema.org provides a list of implementations. Notably C and C++ are missing.

Is there a reason I can't easily find a C++ JSON schema validator?
Doesn't anyone else want a quick way to validate incoming JSON files?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

半步萧音过轻尘 2024-10-18 21:55:54

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

我在谷歌上发现了一些点击:

您还可以将 Python 或 Javascript 解释器插入您的应用程序中,然后只需运行您已找到的验证器实现的本机版本即可。

我无法轻松找到 C++ JSON 模式验证器是否有原因?

我相信 JSON 起源于一种 Web 技术,而 C/C++ 已经不再适合 Web 应用程序实现。

Is there a stable library that can validate JSON against a schema?

I found a couple hits on google:

You could also plug a Python or Javascript interpreter into your app, and simply run the native version of those validator implementations that you've already found.

Is there a reason I can't easily find a C++ JSON schema validator?

I believe JSON originated as a web technology, and C/C++ has fallen out of favor for web app implementation.

顾忌 2024-10-18 21:55:54

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());
  }
}

Valijson is a very good library which depends only on Boost (And I'm actually hoping to change that). It doesn't even depend on any particular JSON parser, providing adapters for most commonly-used libraries like JsonCpp, rapidjson and json11.

The code may seem verbose, but you can always write a helper (example for 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());
  }
}
昵称有卵用 2024-10-18 21:55:54

您可以尝试UniversalContainer(libuc)。 http://www.greatpanic.com/code.html。您正在该库中寻找容器契约/模式检查类。架构格式很笨重,但应该处理您关心的所有内容,并提供有关特定实例无法满足架构的原因的合理报告。

You can try UniversalContainer (libuc). http://www.greatpanic.com/code.html. You're looking for the container contract/schema checking class in this library. The schema format is clunky, but should handle everything you care about and provide reasonable reporting on why a particular instance fails to meet the schema.

旧话新听 2024-10-18 21:55:54

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

Rapidjson

我使用它对模式进行 JSON 验证(大多数情况下)。它看起来像是经过测试并且稳定的(根据 github 存储库,v1.1.0 看起来像是最新版本)。

Is there a stable library that can validate JSON against a schema?

Rapidjson

I'm using it for JSON validation against a schema (for the most). It looks like to be tested and stable (v1.1.0 looks like to be latest release, according to the github repo).

独留℉清风醉 2024-10-18 21:55:54

如果您可以适应多语言方法,Ajv 似乎是一个可靠的 JavaScript 实现。

https://ajv.js.org/

注意:还有一个 ajv-cli

https://github.com/jessedc/ajv-cli

If you can accommodate a polyglot approach, Ajv appears to be a solid JavaScript implementation.

https://ajv.js.org/

Note: There is also an ajv-cli

https://github.com/jessedc/ajv-cli

小耗子 2024-10-18 21:55:54

在 Windows 平台上,无论何种语言,您都可以使用 JSON Essentials for COM/ActiveX由您选择。如果您想使用 MSVC 编译器从 C++ 中使用它,您可以使用 #import 预处理器指令让编译器生成包装器。

其文档包含最常见用途的示例数量 C#、VB 和 JavaScript 中的案例。语言语法是唯一发生变化的东西,这一切都可以在几乎任何支持 COM 的语言中使用相同的库调用来实现。

还值得一提的是,它提供免费许可选项。

以下是使用 JSON Essentials 评估版本:

// Create a new JsonEssentials class instance.
var jess = new ActiveXObject('JsonEssentials_0.JsonEssentials.1');
jess.unlock('jesscomeval');

// Create schema JSON document object.
var schemaDoc = jess.createDocument();

// Load JSON schema.
schemaDoc.load({
    'type': 'array',
    'items': {
        'type': 'integer'
    }
});

// Create schema collection object.
var schemas = jess.createSchemas();

// Add the test schema to the collection.
var schema = schemas.add(schemaDoc, 'uri:test');

// Create JSON document object.
var instanceDoc = jess.createDocument();

// Load JSON, an array of numeric values.
instanceDoc.load([ 0, 1, 2 ]);
 
// Validate the test JSON against the added schema.
var status = schema.validate(instanceDoc);

WScript.Echo(status.success ? 'validated' : 'validation failed');

On Windows platform you can use JSON Essentials for COM/ActiveX regardless of the language of your choice. If you want to use it from C++ using MSVC compiler you can have compiler generated wrappers using the #import pre-processor directive.

Its documentation contains a number of samples for the most common use cases in C#, VB and JavaScript. The language syntax is the only things that changes, it all can be implemented using the same library calls in pretty much any language that supports COM.

It's also worth to mention that it offers free licensing options.

Here is a sample of creating a schema, loading and validating a JSON document using the newly created schema for Windows Script Host (WSH) using JSON Essentials evaluation version:

// Create a new JsonEssentials class instance.
var jess = new ActiveXObject('JsonEssentials_0.JsonEssentials.1');
jess.unlock('jesscomeval');

// Create schema JSON document object.
var schemaDoc = jess.createDocument();

// Load JSON schema.
schemaDoc.load({
    'type': 'array',
    'items': {
        'type': 'integer'
    }
});

// Create schema collection object.
var schemas = jess.createSchemas();

// Add the test schema to the collection.
var schema = schemas.add(schemaDoc, 'uri:test');

// Create JSON document object.
var instanceDoc = jess.createDocument();

// Load JSON, an array of numeric values.
instanceDoc.load([ 0, 1, 2 ]);
 
// Validate the test JSON against the added schema.
var status = schema.validate(instanceDoc);

WScript.Echo(status.success ? 'validated' : 'validation failed');

赠佳期 2024-10-18 21:55:54

您可以查看此方法 https://epub.jku。 at/obvulioa/content/pageview/6390647?query=berardinelli

EMF(Eclipse 建模框架)中提供了 JSON 文档(元架构、架构或架构实例)的内存表示形式。一旦您有了这种内存中表示(保留通常的 JSON 文本符号,因此与您现在使用的任何 JSON 工具兼容),您就可以使用基于 EMF 的技术(如 OCL)以及 MDE 平台(如 Eclipse Epsilon)。

You can have a look to this approach https://epub.jku.at/obvulioa/content/pageview/6390647?query=berardinelli

The in-memory representation of your JSON documents (metaschema, schemas, or schema instances) is provided in EMF (Eclipse Modeling Framework). Once you have this in-memory representation (preserving the usual JSON textual notation, so compliant with any JSON tool you are using now), you can use EMF-based technologies like OCL as well as MDE platforms like Eclipse Epsilon.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文