Question

I am using python-jsonschema for json validation. I have an object with localised texts that are specified inside rfc1766 language code keys as followings:

"Description": {
    "en": "English Description",
    "sv": "Swedish Description",
    "fr": "French Description"
},

I've read in the documentation that I could use the 'format' attribute to check a custom format using a function. So,I wrote a method which takes a string as a parameter and returns True if it is an RFC1766 language string.

@_checks_drafts('rfc1766lang')
def rfc1766lang(instance):
    """some logic, return True if rfc1766"""

However I couldn't find any example on how to apply this to do validation on an object key, not a value.

Is this possible?

I have tried something like below but I couldn't succeed

rfc1766_string_schema_v2 = {
    'type': 'object',
    'format': 'rfc1766lang',    
    'additionalProperties': False
}

I know that it would be much easier if I had the json string as follows. However, this is not an option for now.

"Description": [{
    "lan": "en",
    "text": "Description in English"
}, {
    "lan": "sv",
    "name": "Description in Swedish"
}]
Was it helpful?

Solution

This is a very good and relevant question because this is actually part of the proposed syntax for v5, so the official meta-schema will have to deal with this as well.

JSON Schema cannot specify a "format" for object keys. The only "validation" JSON Schema supports for object keys is patternProperties, which supplies a regular expression.

For language codes, the best you can do is probably something like:

{
    "type": "object",
    "patternProperties": {
        "^[a-zA-Z]+(-[a-zA-Z]+)*$": {...}
    },
    "additionalProperties": false
}

That would limit the data so that it was only allowed properties matching that pattern - but that's not the full validation you're looking for, I'm afraid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top