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%
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 โ€บ 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 605 users
Forked by 154 users
Languages ย  C++ 86.2% | CMake 12.3% | Python 1.3% | Shell 0.2%
๐ŸŒ
GitHub
github.com โ€บ domoslabs โ€บ jsonc-daccord
A lightweight JSON Schema validator using json-c library
A lightweight JSON Schema validator using json-c library - getCUJO/jsonc-daccord
Author ย  getCUJO
๐ŸŒ
JSON Schema Validator
jsonschemavalidator.net
JSON Schema Validator - Newtonsoft
This schema validator is built using Json.NET Schema and C#.
๐ŸŒ
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 โ€บ tools
JSON Schema - Tools
Bowtie is a meta-validator for JSON Schema implementations and it provides compliance reports.
Find elsewhere
๐ŸŒ
Liquid Technologies
liquid-technologies.com โ€บ online-json-schema-validator
Free Online JSON Validator (JSON Schema)
The Free Community Edition of Liquid Studio comes with an advanced JSON Editor, packed with many helpful features including JSON document validation. Data Security Warning - Tick this box to confirm you understand all data is stored on our servers for processing and may be retained for service improvement. If you have sensitive data, please Download the Free Liquid Studio Community Edition and use the tools directly from your desktop. ... Additional Free Tools - Includes XML Editor, XSD Editor, JSON Editor, JSON Schema Editor, Data Conversion, Web Tools
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...

๐ŸŒ
JSON Schema
json-schema.org โ€บ understanding-json-schema โ€บ reference โ€บ conditionals
JSON Schema - Conditional schema validation
These countries have different postal code formats, and we want to select which format to validate against based on the country. If the address is in the United States, the postal_code field is a "zipcode": five numeric digits followed by an optional four digit suffix.
๐ŸŒ
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
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
๐ŸŒ
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 }
๐ŸŒ
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.
Top answer
1 of 2
2

There is Json.NET Schema for performing validation.

2 of 2
1

Hi @DEEPAK KUMPALA ,

You can use Deserialize subsections of a JSON payload to finish it.

I test it under. Net6.0.

Below is the code:

using System.Collections.Generic;  
using System;  
using System.Text.Json;  
  
namespace DeserializeExtra  
{  
	public class Rootobject  
	{  
		public int pageNumber { get; set; }  
		public int pageSize { get; set; }  
		public Datum[] data { get; set; }  
	}  
  
	public class Datum  
	{  
		public string Id { get; set; }  
		public DateTime LastModified { get; set; }  
		public bool IsActive { get; set; }  
		public Device[] Devices { get; set; }  
	}  
  
	public class Device  
	{  
		public string Id { get; set; }  
		public bool IsActive { get; set; }  
		public string SerialNumber { get; set; }  
	}  
  
	public class Program  
	{  
		public static void Main()  
		{  
			string jsonString =  
@" {  
 	""pageNumber"": 1,  
 	""pageSize"": 250,  
 	""data"": [{  
 		""Id"": ""6817662d"",  
 		""LastModified"": ""2022-04-09T06:40:40+00:00"",  
 		""IsActive"": true,  
 		""Devices"": [{  
 				""Id"": ""d58f034b"",  
 				""IsActive"": true,  
 				""SerialNumber"": ""754""  
 			},  
 			{  
 				""Id"": ""005056963bac"",  
 				""IsActive"": true,  
 				""SerialNumber"": ""707""  
 			}  
 		]  
 	}]  
 }  
";  
  
			Rootobject? rootobject =  
				JsonSerializer.Deserialize(jsonString);  
			  
			foreach (var datum in rootobject.data)  
			{  
				if (datum.Devices != null) {  
					Console.WriteLine("It at least one device present under Devices node");  
				}  
				foreach (var device in datum.Devices)  
				{  
					Console.WriteLine($"Id:{device.Id}");  
				}  
			}  
		}  
	}  
}  

Output:


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ json โ€บ json_schema.htm
JSON - Schema
You can check a http://json-schema.org for the complete list of keywords that can be used in defining a JSON schema. The above schema can be used to test the validity of the following JSON code โˆ’
๐ŸŒ
CodeGuru
codeguru.com โ€บ home โ€บ c#
Validating JSON with JSON Schema in C# | CodeGuru
August 9, 2021 - For detailed implementation of JSON Schema, refer to the preceding link. A true valid property signals that the JSON is valid. If the validation fails, it will be false and the errors property will contain an array of error messages.
๐ŸŒ
json-everything
docs.json-everything.net โ€บ schema โ€บ basics
JsonSchema.Net Basics | json-everything
2 days ago - Once defined, the schema evaluates the instance, providing feedback on what errors occurred, including where in the instance and in the schema produced them. JsonSchema.Net implements keywords using singleton keyword handlers. These handlers are responsible for validating that the keyword data ...
๐ŸŒ
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.