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

I found a couple hits on google:

  • From the Chromium project: http://aaronboodman-com-v1.blogspot.com/2010/11/c-version-of-json-schema.html
  • http://avro.apache.org/docs/1.4.1/api/cpp/html/index.html

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.

Answer from Merlyn Morgan-Graham on Stack Overflow
๐ŸŒ
GitHub
github.com โ€บ helmut-jacob โ€บ jsonschema-c
GitHub - helmut-jacob/jsonschema-c: JSON schema validation and parsing based on libjson-c
JSON schema validation for json-c library. jsonschema-c is a schema validation based on the json-c library and the V4 draft of json schema standard. The library is composed of two components: schema validator and instance validator.
Starred by 18 users
Forked by 11 users
Languages ย  C 100.0% | C 100.0%
๐ŸŒ
JSON Schema Validator
jsonschemavalidator.net
JSON Schema Validator - Newtonsoft
This schema validator is built using Json.NET Schema and C#.
Top answer
1 of 7
18

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

I found a couple hits on google:

  • From the Chromium project: http://aaronboodman-com-v1.blogspot.com/2010/11/c-version-of-json-schema.html
  • http://avro.apache.org/docs/1.4.1/api/cpp/html/index.html

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.

2 of 7
8

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());
  }
}
๐ŸŒ
GitHub
github.com โ€บ domoslabs โ€บ jsonc-daccord
GitHub - getCUJO/jsonc-daccord: A lightweight JSON Schema validator using json-c library
jsonc-daccord is a JSON Schema validation library written in C, and is taking advantage of the json-c library.
Author ย  getCUJO
๐ŸŒ
JSON Schema
json-schema.org โ€บ tools
JSON Schema - Tools
Bowtie is a meta-validator for JSON Schema implementations and it provides compliance reports.
๐ŸŒ
GitHub
github.com โ€บ pboettch โ€บ json-schema-validator
GitHub - pboettch/json-schema-validator: JSON schema validator for JSON for Modern C++ ยท GitHub
JSON schema validator for JSON for Modern C++. Contribute to pboettch/json-schema-validator development by creating an account on GitHub.
Starred by 604 users
Forked by 154 users
Languages ย  C++ 86.2% | CMake 12.3% | Python 1.3% | Shell 0.2%
๐ŸŒ
Liquid Technologies
liquid-technologies.com โ€บ online-json-schema-validator
Free Online JSON Validator (JSON Schema)
Validates that a JSON document is syntactically valid, and that it conforms to the definition described by a JSON Schema.
Find elsewhere
๐ŸŒ
Ajv
ajv.js.org
Ajv JSON schema validator
It allows implementing complex data validation logic via declarative schemas for your JSON data, without writing code.
๐ŸŒ
JSON Schema
json-schema.org
JSON Schema
Adopt JSON Schema with an expansive range of community-driven tools, libraries, and frameworks across many programming languages. ... Discover JSON Schema tooling to help your organization leverage the benefits of JSON Schema. Because JSON Schema is much more than a Specification, it is a vibrant ecosystem of Validators, Generators, Linters, and other JSON Schema Utilities made by this amazing Community.Explore
Top answer
1 of 4
20

I think that you just need to add

'additionalProperties': false

to your schema. This will stop unknown properties being provided.

So now your results will be:- True, False, False

test code....

void Main()
{
var schema = JsonSchema.Parse(
@"{
    'type': 'object',
    'properties': {
        'name': {'type':'string'},
        'hobbies': {'type': 'array'}
    },
    'additionalProperties': false
    }");

IsValid(JObject.Parse(
@"{
    'name': 'James',
    'hobbies': ['.NET', 'LOLCATS']
  }"), 
schema).Dump();

IsValid(JObject.Parse(
@"{
    'surname': 2,
    'hobbies': ['.NET', 'LOLCATS']
  }"), 
schema).Dump();

IsValid(JObject.Parse(
@"{
    'name': 2,
    'hobbies': ['.NET', 'LOLCATS']
  }"), 
schema).Dump();
}

public bool IsValid(JObject obj, JsonSchema schema)
{
    return obj.IsValid(schema);
}

output :-

True
False
False

You could also add "required":true to the fields that must be supplied that way you can return a message with details of missing/invalid fields:-

Property 'surname' has not been defined and the schema does not allow additional     properties. Line 2, position 19. 
Required properties are missing from object: name. 

Invalid type. Expected String but got Integer. Line 2, position 18. 
2 of 4
4

Ok i hope this will help.

This is your schema:

 public class test
{
    public string Name { get; set; }
    public string ID { get; set; }

}

This is your validator:

/// <summary>
    /// extension that validates if Json string is copmplient to TSchema.
    /// </summary>
    /// <typeparam name="TSchema">schema</typeparam>
    /// <param name="value">json string</param>
    /// <returns>is valid?</returns>
    public static bool IsJsonValid<TSchema>(this string value)
        where TSchema : new()
    {
        bool res = true;
        //this is a .net object look for it in msdn
        JavaScriptSerializer ser = new JavaScriptSerializer();
        //first serialize the string to object.
        var obj = ser.Deserialize<TSchema>(value);

        //get all properties of schema object
        var properties = typeof(TSchema).GetProperties();
        //iterate on all properties and test.
        foreach (PropertyInfo info in properties)
        {
            // i went on if null value then json string isnt schema complient but you can do what ever test you like her.
            var valueOfProp = obj.GetType().GetProperty(info.Name).GetValue(obj, null);
            if (valueOfProp == null)
                res = false;
        }

        return res;
    }

And how to use is:

string json = "{Name:'blabla',ID:'1'}";
        bool res = json.IsJsonValid<test>();

If you have any question please ask, hope this helps, please take into consideration that this isn't a complete code without exception handling and such...

๐ŸŒ
Mockoon
mockoon.com โ€บ tools โ€บ json-schema-validator
Mockoon - Online JSON Schema validator
It allows you to specify the type of each field, the required fields, and any constraints on the data. The JSON schema format is defined by the JSON Schema standard. JSON schemas are useful for validating JSON data, generating documentation, and providing a contract for APIs.
๐ŸŒ
JSONLint
jsonlint.com โ€บ json-schema
JSON Schema Validator - Validate JSON Against Schema | JSONLint | JSONLint
Validate your JSON data against a JSON Schema. Catch structural errors, type mismatches, and missing required fields before they cause bugs.
๐ŸŒ
Rapidjson
rapidjson.org โ€บ md_doc_schema.html
RapidJSON: Schema
First of all, you need to parse a JSON Schema into Document, and then compile the Document into a SchemaDocument. Secondly, construct a SchemaValidator with the SchemaDocument. It is similar to a Writer in the sense of handling SAX events. So, you can use document.Accept(validator) to validate a document, and then check the validity.
๐ŸŒ
JSON Schema
json-schema.org โ€บ draft โ€บ 2020-12 โ€บ json-schema-validation
JSON Schema Validation: A Vocabulary for Structural Validation of JSON
This document specifies a vocabulary for JSON Schema to describe the meaning of JSON documents, provide hints for user interfaces working with JSON data, and to make assertions about what a valid document must look like.ยถ ยท The issues list for this draft can be found at https://github.com/json-schema-org/json-schema-spec/issues.ยถ
๐ŸŒ
JSON Schema
json-schema.org โ€บ learn โ€บ getting-started-step-by-step
Creating your first schema
The most basic schema is a blank JSON object, which constrains nothing, allows anything, and describes nothing: ... By adding validation keywords to the schema, you can apply constraints to an instance.
๐ŸŒ
JSON Editor Online
jsoneditoronline.org โ€บ home โ€บ validate โ€บ json-schema-validator
JSON Schema validator: a powerful way to check JSON data | Indepth
May 31, 2023 - JSON Schema defines the following types: array, object, string, number, integer, boolean, and null. Note that it is possible to create nested objects and arrays, by defining one of the properties (or array items) as an array or object again. Now comes the interesting part: we can use validation keywords to define that the properties โ€œnameโ€ and โ€œageโ€ are required (properties are optional by default), that age must be a positive number, and that the email must contain an actual valid email address.
๐ŸŒ
Newtonsoft
newtonsoft.com โ€บ json โ€บ help โ€บ html โ€บ JsonSchema.htm
Validating JSON with JSON Schema
string json = @"{ 'name': 'James', 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] }"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); JsonValidatingReader validatingReader = new JsonValidatingReader(reader); validatingReader.Schema = JsonSchema.Parse(schemaJson); IList<string> messages = new List<string>(); validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message); JsonSerializer serializer = new JsonSerializer(); Person p = serializer.Deserialize<Person>(validatingReader); ... The simplest way to get a JsonSchema object is to load it from a string or a file. ... // load from a string JsonSchema schema1 = JsonSchema.Parse(@"{'type':'object'}"); // load from a file using (TextReader reader = File.OpenText(@"c:\schema\Person.json")) { JsonSchema schema2 = JsonSchema.Read(new JsonTextReader(reader)); // do stuff }
๐ŸŒ
Jsonschema
jsonschema.dev
JSON Schema Validation
JSON Schema Validation, in browser, using ajv, with linting, and shareable schemas
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ json โ€บ json_schema.htm
JSON - Schema
It was written under IETF draft which expired in 2011. JSON Schema โˆ’ ยท Describes your existing data format. Clear, human- and machine-readable documentation. Complete structural validation, useful for automated testing.