json 数据验证怎么做

本贴最后更新于 508 天前,其中的信息可能已经斗转星移

json schema 用来描述一个 json 数据的结构,这在验证json数据时非常有用,以下操作是常用的一些验证规则。

校验是否包含 access_token 和 token_type 字段:

{
    "type": "object",
    "required": ["access_token", "token_type"],
}

校验字段类型:

{
    "type": "object",
    "required": ["access_token", "token_type"],
    "properties": {
        "access_token": {"type": "string"},
        "token_type": {"type": "string"}
    }
}

检验字段个数:

{
  "type": "object",
  "minProperties": 2,
  "maxProperties": 3
}

校验字段是否匹配某个规则(正则)

{
    "required": ["msg"],
    "properties": {
        "msg": {"pattern": "Incorrecdd account or password"}
    }
}

校验字符串长度

ajson = {"token": "abc", "now": "2017-03-23"}

# 字符串长度
schema = {
  "required": ["token"],
  "properties": {
    "token": {
      "type": "string",
      "minLength": 3,
      "maxLength": 3
    }
  }
}

校验字符串是否为日期格式

# 日期
ajson = {"token": "abc", "now": "2017-03-23"}
schema = {
  "required": ["now"],
  "properties": {
    "now": {
      "type": "string",
      "format": "date"
    }
  }
}
result = jsonschema.validate(ajson, schema=schema)

检验字符串是否为邮箱

# 邮箱
ajson = {"email": "wagyu2016@163.com"}
schema = {
  "required": ["email"],
  "properties": {
    "email": {
      "type": "string",
      "format": "email"
    }
  }
}
result = jsonschema.validate(ajson, schema=schema)
print(result)

验证数字范围:

{
  "type": "number",
  "minimum": 0,
  "exclusiveMaximum": 100
}

用来表述数据类型的有:

校验字段长度

{"type": "string", "minLength": 2, "maxLength": 3}

校验 array 元素是否都为number

{
  "type": "array",
  "items": {
    "type": "number"
  }
}

分别校验 array 中每一个元素:

{
  "type": "array",
  "items": [
    { "type": "number" },
    { "type": "string" },
    { "enum": ["Street", "Avenue", "Boulevard"] },
    { "enum": ["NW", "NE", "SW", "SE"] }
  ]
}

校验元素值是否唯一

{
  "type": "array",
  "uniqueItems": true
}

在 Python 中使用 jsonschema, 首先导入 jsonschema , 使用 validate 函数验证是否符合规则。

import jsonschema
jsonschema.validate(obj, schema=schema)
回帖
请输入回帖内容 ...