Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

jsonschema - How would you design JSON Schema for an arbitrary key?

I have the following JSON output data:

{
   "label_name_0" : 0,
   "label_name_5" : 3,
   .
   .
   .
   "label_name_XXX" : 4
}

The output is simple: a key[1] name associated with integer value. If the key name doesn't change, I can easily come up with JSON Schema similar to this:

    {
        "type": "array"
        "title": "Data output",
        "items" :{ 
            "properties": {
                "label_name": {
                   "type": "integer",
                   "default": 0,
                   "readonly": True,
            }
        }
    },

Since the key name itself is not known and keep changing, I have to design schema for it. The only thing I know is that the key is string and not more than 100 characters. How do I define a JSON Schema for the key lable_name_xxx that keeps changing.

[1] Not sure if I am using the right terminology

question from:https://stackoverflow.com/questions/16222633/how-would-you-design-json-schema-for-an-arbitrary-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On json-schema.org you will find something appropriate in the Advanced Examples section. You can define patternProperties inside an object.

{
    "type": "object",
    "properties": {
        "/": {}
    },
    "patternProperties": {
        "^(label_name_[0-9]+)+$": { "type": "integer" }
    },
    "additionalProperties": false,
 }

The regular expression (label_name_[0-9]+)+ should fit your needs. In JSON Schema regular expressions are explicitly anchored with ^ and $. The regular expressions defines, that there has to be at least one property (+). The property consists of label_name_ and a number between 0 and 9 whereas there has to be at least one number ([0-9]+), but there can also arbitrary many of them.

By setting additionalProperties to false it constrains object properties to match the regular expression.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...