如何使用JSON Schema验证YAML并确保dep名称唯一性?
YAML验证:转JSON + JSON Schema校验完整指南
我来帮你一步步搞定这个验证流程,从YAML转JSON,到编写正确的JSON Schema实现dep名称唯一校验,再到实际执行验证,都给你讲清楚:
第一步:把YAML转换成JSON
首先得把你的YAML文件转成JSON格式,这里给你两种常用的代码实现方式,选你熟悉的语言就行:
Python(用PyYAML库)
先装依赖:
pip install pyyaml
然后写个简单的转换脚本:
import yaml import json # 读取你的YAML文件 with open("your_input.yaml", "r") as yaml_file: yaml_content = yaml.safe_load(yaml_file) # 转成JSON并保存 with open("output.json", "w") as json_file: json.dump(yaml_content, json_file, indent=2)
Node.js(用js-yaml库)
先装依赖:
npm install js-yaml
转换脚本:
const yaml = require('js-yaml'); const fs = require('fs'); try { // 读取YAML内容并转成JSON const yamlData = yaml.load(fs.readFileSync('your_input.yaml', 'utf8')); // 写入JSON文件 fs.writeFileSync('output.json', JSON.stringify(yamlData, null, 2)); } catch (error) { console.error('转换出错:', error); }
第二步:编写正确的JSON Schema实现dep名称唯一校验
你提供的初始Schema有几个小问题需要修正:比如把name的类型设成了array,但你的YAML里name是字符串;另外正则表达式不需要用斜杠包裹。
根据你的需求,我分两种常见场景来写Schema:
场景1:dep是数组,每个dep项的name不能重复
如果你的实际需求是有多个dep条目(比如YAML里dep是数组),要确保每个dep的name唯一,用这个Schema:
{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "dep": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string", "pattern": "^[A-Za-z0-9_-.]+$" }, "path": {"type": "string"}, "requires": {"type": "object", "properties": {"name": {"type": "string"}}}, "properties": {"type": "object", "properties": {"name": {"type": "string"}}} }, "required": ["name"] }, // 校验所有dep的name唯一 "allOf": [ { "not": { "items": { "oneOf": [ { "contains": { "properties": {"name": {"$ref": "#/properties/dep/items/properties/name"}}, "required": ["name"] } } ] } } } ] }, "name": {"type": "string", "pattern": "^[A-Za-z0-9_-.]+$"}, "path": {"type": "string"}, "requires": {"type": "object", "properties": {"name": {"type": "string"}}} }, "required": ["dep"] }
场景2:dep是单个对象,确保dep.name和顶层name不重复
如果你的YAML结构里dep是单个对象,要确保它的name和顶层的name不重复,用这个Schema:
{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "dep": { "type": "object", "properties": { "name": { "type": "string", "pattern": "^[A-Za-z0-9_-.]+$" }, "path": {"type": "string"}, "requires": {"type": "object", "properties": {"name": {"type": "string"}}}, "properties": {"type": "object", "properties": {"name": {"type": "string"}}} }, "required": ["name"] }, "name": { "type": "string", "pattern": "^[A-Za-z0-9_-.]+$", // 确保顶层name和dep.name不一样 "not": {"enum": [{"$ref": "#/properties/dep/properties/name"}]} }, "path": {"type": "string"}, "requires": {"type": "object", "properties": {"name": {"type": "string"}}} }, "required": ["dep", "name"] }
第三步:执行校验
最后用工具来验证你的JSON数据是否符合Schema:
Python(用jsonschema库)
先装依赖:
pip install jsonschema
校验脚本:
import json from jsonschema import validate # 加载JSON数据和Schema with open("output.json", "r") as f: json_data = json.load(f) with open("validation_schema.json", "r") as f: schema = json.load(f) # 执行校验 try: validate(instance=json_data, schema=schema) print("✅ 数据通过Schema校验!") except Exception as e: print(f"❌ 校验失败:{e}")
Node.js(用ajv库)
先装依赖:
npm install ajv
校验脚本:
const Ajv = require('ajv'); const ajv = new Ajv(); const fs = require('fs'); // 加载数据和Schema const jsonData = JSON.parse(fs.readFileSync('output.json', 'utf8')); const schema = JSON.parse(fs.readFileSync('validation_schema.json', 'utf8')); // 编译并执行校验 const validate = ajv.compile(schema); const isValid = validate(jsonData); if (isValid) { console.log('✅ 数据通过Schema校验!'); } else { console.error('❌ 校验失败:', validate.errors); }
内容的提问来源于stack exchange,提问作者07_05_GuyT
相关产品推荐
相关产品推荐

