python - 我可以在 Python 中验证 JSON 模式中字符串的内容吗

标签 python json

我想指定一个字符串只能是四个值之一。我怎样才能使用 jsonschema 做到这一点图书馆?

示例代码:

"value_params": {
    "required": ["positions", "userId"],
    "properties": {
        "userId": {"type": "integer"},
        "positions": {
            "type": "array",
            "minItems": 1,
            "items": {
                "type": "object",
                "required": ["partnerUserId", "userType"],
                "properties": {
                    "partnerUserId": {"type": "integer"},
                    "userType": {"type": "string"}
                },
                "additionalProperties": False
            }
        }
    },
    "additionalProperties": False
},

以上效果很好。我需要添加什么才能要求 userType 成为仅有的 4 个值之一?

最佳答案

看看这个 example schema .

使用enum将值限制为一组固定值:

"label": {
    "type": "string",
    "enum": ["value1", "value2", "value3", "value4"]
}

还可以定义正则表达式模式:

"label": {
    "type": "string",
    "pattern": "^value1|value2|value3|value4$"
}

关于python - 我可以在 Python 中验证 JSON 模式中字符串的内容吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327970/

相关文章:

python - scikit-learn 中预计算内核的网格搜索中的嵌套交叉验证

json - hive 从JSON错误

javascript - 如何使用 _bsontype 属性处理来自 mongoDB 的文档

javascript - 为什么我收到有关 "unexpected non-whitespace after JSON data"的错误消息

python - 关闭开发服务器上的 Celery 任务延迟

python - scikit-learn 中分类算法的文本特征输入格式

html - 表格enctype "application/json"可用吗?

javascript - 从 json 填充可观察数组

python - 根据索引列表更改 Pandas 列的值

python - 使用 NaN 值迭代连接 pandas 中的列