求推荐Node.js中可查询JSON Schema指定路径的库
适用的Node.js库推荐
以下几个库可以满足你在JSON Schema中查询指定路径定义的需求,它们适配JSON Schema的特殊结构(比如数组的定义在items字段),能正确解析category.id、tags[0].id这类路径:
1. json-schema-traverse
专门用于遍历JSON Schema的工具,支持通过JSON Pointer定位到目标schema节点,你可以先把业务路径转换为对应的Pointer,再进行查询:
const traverse = require('json-schema-traverse'); // 示例JSON Schema const yourSchema = { type: 'object', properties: { category: { type: 'object', properties: { id: { type: 'string' } } }, tags: { type: 'array', items: { type: 'object', properties: { id: { type: 'integer' } } } } } }; // 把业务路径转换为JSON Pointer的工具函数 const pathToPointer = (path) => { // 处理数组索引,比如tags[0] → tags/items const processed = path.replace(/\[(\d+)\]/g, '/items'); return `/${processed.replace(/\./g, '/')}`; }; // 查询指定路径的schema定义 const findSchemaDef = (schema, path) => { const pointer = pathToPointer(path); let result; traverse(schema, { cb: (node, ptr) => { if (ptr === pointer) { result = node; } } }); return result; }; // 使用示例 console.log(findSchemaDef(yourSchema, 'category.id')); console.log(findSchemaDef(yourSchema, 'tags[0].id'));
2. @stoplight/json-schema
Stoplight推出的JSON Schema工具库,内置了路径查询方法,对JSON Schema的结构支持更完善:
const { getSchemaAtPath } = require('@stoplight/json-schema'); const yourSchema = { /* 你的JSON Schema */ }; // 手动转换业务路径为JSON Schema的Pointer格式 const getPointerFromPath = (path) => { let pointer = path.replace(/\[(\d+)\]/g, '/items'); pointer = pointer.replace(/\./g, '/properties/'); return `#/properties/${pointer}`; }; // 查询示例 const categoryIdDef = getSchemaAtPath(yourSchema, getPointerFromPath('category.id')); const tagItemIdDef = getSchemaAtPath(yourSchema, getPointerFromPath('tags[0].id')); console.log(categoryIdDef, tagItemIdDef);
3. jsonpointer
基础的JSON Pointer操作库,配合自定义的路径转换逻辑,也能实现需求。它直接操作JSON Schema对象,适合轻量场景:
const jsonpointer = require('jsonpointer'); const yourSchema = { /* 你的JSON Schema */ }; const convertPathToPointer = (path) => { return `/${path.replace(/\[(\d+)\]/g, '/items').split('.').join('/')}`; }; // 查询tags[0].id的定义 const pointer = convertPathToPointer('tags[0].id'); const schemaDef = jsonpointer.get(yourSchema, pointer); console.log(schemaDef);
说明
普通jsonpath库无法处理是因为它们针对普通JSON的数组元素设计,而JSON Schema中数组的项定义在items字段,上述库都考虑了这个特殊结构,能正确映射tags[0].id这类路径到对应的schema节点。
内容的提问来源于stack exchange,提问作者Shravan Jain
相关产品推荐
相关产品推荐

