Search code examples
c++jsonjsonschemarapidjson

How to get RapidJSON schema to deal with default properties


I have the following JSON schema, which requires both id and content but defaults the latter to an empty string.

{
    "type": "object",
    "properties": {
        "id": { "type": "string" },
        "content": { "type": "string", "default": "" }
    },
    "required": [ "id", "content" ],
    "additionalProperties": false
}

I'm trying to validate the following JSON string:

{
    "id": "some id"
}

For that, I have the following code:

rapidjson::Document document;
document.Parse(schemaJson.c_str());

rapidjson::SchemaDocument schemaDocument(document);
rapidjson::SchemaValidator validator(schemaDocument);

rapidjson::Document modelDoc;
modelDoc.Parse(modelJson.c_str());

modelDoc.Accept(validator); // Complains about missing property

The accept call fails the validation even though the property has a default value.

The RapidJSON schema documentation claims it conforms to the JSON Schema draft 4.

Does anyone know what I may be doing wrong?

Thanks.


Solution

  • As of today, your beef is with JSON Schema validation spec, not with RapidJSON:

    4.3. Default values for missing keywords

    Some keywords, if absent, MAY be regarded by implementations as having a default value. In this case, the default value will be mentioned.

    Consequence: a processor is allowed to ignore the missing values even if they have a default value provided and still be conforming to JSON-schema validation specification

    5.4.3. required

    5.4.3.2. Conditions for successful validation An object instance is valid against this keyword if its property set contains all elements in this keyword's array value.

    Consequence: a validator must not ignore missing but required properties.


    Put the two together and what gives? RapidJSON can still claim conformance to JSON Schema validation, even if it does not consider the default values for required properties during schema validation.

    You can still lodge an enhancement request in the issues page of RapidJson project