如何在Postman中用递归函数比较两个响应JSON并返回不匹配信息
递归实现JSON深度对比并返回所有不匹配错误信息
核心思路
通过递归遍历JSON的每一层节点,针对基本类型、对象、数组三种情况分别做校验,全程追踪当前节点的路径,收集所有不匹配细节(值不匹配、类型不匹配、属性/元素缺失/多余),最终根据错误列表长度返回pass或所有错误信息。
代码实现(JavaScript)
function compareJSON(json1, json2, path = '') { const errors = []; // 校验类型一致性 const type1 = typeof json1; const type2 = typeof json2; if (type1 !== type2) { errors.push(`路径${path || '根节点'}:类型不匹配,预期${type1},实际${type2}`); return errors; } // 处理基本类型(非对象/数组,含null) if (type1 !== 'object' || json1 === null || json2 === null) { if (json1 !== json2) { errors.push(`路径${path || '根节点'}:值不匹配,预期${JSON.stringify(json1)},实际${JSON.stringify(json2)}`); } return errors; } // 区分数组和对象类型 const isArray1 = Array.isArray(json1); const isArray2 = Array.isArray(json2); if (isArray1 !== isArray2) { errors.push(`路径${path || '根节点'}:类型不匹配,预期${isArray1 ? '数组' : '对象'},实际${isArray2 ? '数组' : '对象'}`); return errors; } if (isArray1) { // 数组对比:处理长度差异,递归校验每个元素 const maxLen = Math.max(json1.length, json2.length); for (let i = 0; i < maxLen; i++) { const currentPath = path ? `${path}[${i}]` : `[${i}]`; if (i >= json1.length) { errors.push(`路径${currentPath}:数组存在额外元素,值为${JSON.stringify(json2[i])}`); } else if (i >= json2.length) { errors.push(`路径${currentPath}:数组缺失元素,预期值为${JSON.stringify(json1[i])}`); } else { errors.push(...compareJSON(json1[i], json2[i], currentPath)); } } } else { // 对象对比:遍历所有键,处理属性缺失/多余,递归校验属性值 const allKeys = new Set([...Object.keys(json1), ...Object.keys(json2)]); for (const key of allKeys) { const currentPath = path ? `${path}.${key}` : key; if (!(key in json1)) { errors.push(`路径${currentPath}:对象存在多余属性,值为${JSON.stringify(json2[key])}`); } else if (!(key in json2)) { errors.push(`路径${currentPath}:对象缺失属性,预期值为${JSON.stringify(json1[key])}`); } else { errors.push(...compareJSON(json1[key], json2[key], currentPath)); } } } return errors; } // 测试示例 const json1 = { "id": 1, "product": { "productId": "456", "product_detail": [ { "name": { "value": 1 } }, { "name": { "value": 2 } } ] } }; const json2 = { "id": 1, "product": { "productId": "123", "product_info": [ { "name": [{ "value": 3 }] }, { "name": { "value": 4 } } ] } }; // 执行对比并输出结果 const mismatchErrors = compareJSON(json1, json2); console.log(mismatchErrors.length === 0 ? 'pass' : mismatchErrors.join('\n'));
示例运行输出
路径product.productId:值不匹配,预期"456",实际"123" 路径product.product_detail:对象缺失属性,预期值为[{"name":{"value":1}},{"name":{"value":2}}] 路径product.product_info:对象存在多余属性,值为[{"name":[{"value":3}]},{"name":{"value":4}}]
关键细节说明
- 路径追踪:通过递归参数
path记录当前节点的层级路径,错误信息能精确定位不匹配位置 - 类型全覆盖:包含基本类型(字符串、数字、布尔、null)、对象、数组的全类型校验
- 无遗漏校验:不仅对比值,还处理属性/元素的缺失、多余情况,以及类型不匹配问题
- 递归终止条件:遇到基本类型或null时停止递归,直接对比值
内容的提问来源于stack exchange,提问作者user15083770
相关产品推荐
相关产品推荐

