如何在深度嵌套的JSON中为$schema设置绝对路径
解决方案
方法1:利用IDE支持的项目根目录变量
主流IDE(如VS Code)支持用${workspaceFolder}变量指代项目根目录,不管你的JSON文件在多少层子目录下,都能通过这个变量直接指向node_modules里的Schema文件。示例:
{ "$schema": "${workspaceFolder}/node_modules/your-package-name/schema-definition.json" }
这个变量会被IDE自动解析为当前打开项目的根目录路径,完美解决多层目录相对路径混乱的问题。
方法2:IDE全局Schema关联(无需修改JSON文件)
如果不想给每个JSON文件手动添加$schema,可以在IDE的配置文件里批量关联Schema。以VS Code为例,在项目根目录的.vscode/settings.json中添加如下配置:
{ "json.schemas": [ { "fileMatch": ["**/api-responses/**/*.json"], // 匹配你的所有录制JSON文件路径 "url": "./node_modules/your-package-name/schema-definition.json" } ] }
配置后,IDE会自动给匹配到的所有JSON文件应用指定的Schema,提供编码辅助和校验,不用修改任何JSON文件内容。
方法3:用脚本自动生成正确的相对路径
如果必须在JSON文件中写入实际的相对路径,可以写一个简单的Node.js脚本,遍历所有JSON文件,自动计算并添加指向Schema的相对路径:
const fs = require('fs').promises; const path = require('path'); // 替换为你的Schema实际路径和JSON文件根目录 const targetSchemaPath = path.resolve(__dirname, 'node_modules/your-package-name/schema-definition.json'); const jsonRootDir = path.resolve(__dirname, 'api-responses'); async function processJsonFiles(dir) { const entries = await fs.readdir(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); if (entry.isDirectory()) { await processJsonFiles(fullPath); } else if (entry.name.endsWith('.json')) { const relativeSchemaPath = path.relative(path.dirname(fullPath), targetSchemaPath); const content = JSON.parse(await fs.readFile(fullPath, 'utf8')); // 避免重复添加 if (content.$schema !== relativeSchemaPath) { content.$schema = relativeSchemaPath; await fs.writeFile(fullPath, JSON.stringify(content, null, 2)); } } } } processJsonFiles(jsonRootDir).catch(console.error);
运行这个脚本后,所有JSON文件都会自动带上正确的相对路径$schema属性,后续新增文件也可以重新运行脚本更新。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

