如何用Python的jsonschema实现FITS格式单位的自定义校验?
实现自定义FITS单位格式的JSON Schema校验器
问题背景
我有如下JSON Schema,要求unit字段必须符合FITS单位规范:
type: object properties: unit: description: Unit of this column. Must be FITS conform. type: string
为了明确校验规则,我给unit字段添加了自定义format属性:
type: object properties: unit: description: Unit of this column. Must be FITS conform. type: string format: fitsunit
校验FITS单位合规性可以用Astropy库实现(校验失败时会抛出异常):
import astropy.units as u u.Unit(col["unit"], format=u.format.Fits)
现在需要用jsonschema.FormatChecker.checks装饰器实现对应的自定义格式校验器。
实现步骤
1. 导入依赖库
需要导入jsonschema的核心校验类,以及Astropy的单位模块:
import astropy.units as u from jsonschema import FormatChecker, ValidationError
2. 编写自定义格式校验器
用@FormatChecker.checks("fitsunit")装饰器定义校验函数,内部封装Astropy的校验逻辑,将异常转换为jsonschema标准的验证错误:
@FormatChecker.checks("fitsunit") def check_fits_unit(value): if not isinstance(value, str): raise ValidationError(f"FITS unit必须是字符串类型,实际为{type(value).__name__}") try: # 调用Astropy校验FITS单位格式 u.Unit(value, format=u.format.Fits) return True except Exception as e: raise ValidationError(f"无效的FITS单位 '{value}':{str(e)}") from e
3. 启用校验器验证数据
创建FormatChecker实例,在调用jsonschema.validate时传入该实例,即可触发自定义格式校验:
from jsonschema import validate # 定义带自定义format的JSON Schema schema = { "type": "object", "properties": { "unit": { "description": "Unit of this column. Must be FITS conform.", "type": "string", "format": "fitsunit" } } } # 测试合规数据 valid_data = {"unit": "deg"} validate(instance=valid_data, schema=schema, format_checker=FormatChecker()) # 测试不合规数据 invalid_data = {"unit": "invalid_unit"} try: validate(instance=invalid_data, schema=schema, format_checker=FormatChecker()) except ValidationError as e: print(f"校验失败: {e.message}")
关键说明
- 先判断输入类型为字符串,避免Astropy的报错信息不够直观
- 将Astropy的异常包装为
jsonschema.ValidationError,保持错误提示的统一性 - 调用
validate时必须传入format_checker=FormatChecker(),否则自定义格式校验不会生效
内容的提问来源于stack exchange,提问作者olebole
相关产品推荐
相关产品推荐

