JSON 路径测试集成指南与工作流自动化

523 字
3 分钟
JSON 路径测试集成指南与工作流自动化

JSON 路径测试集成指南#

JSON 路径测试集成指南与工作流自动化#

介绍#

将 JSONPath 测试集成到自动化工作流中,可以实现数据提取逻辑的自动校验。

集成场景#

场景 1:自动化测试集成#

// Jest 测试中使用 JSONPath
const jp = require('jsonpath');
describe('API Response Validation', () => {
test('should return valid product IDs', async () => {
const response = await fetch('/api/products');
const data = await response.json();
const ids = jp.query(data, '$.products[*].id');
expect(ids.length).toBeGreaterThan(0);
expect(ids.every(id => typeof id === 'number')).toBe(true);
});
});

场景 2:GitHub Actions 数据校验#

name: Validate JSON Data
on: [push]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate JSONPath expressions
run: |
node -e "
const jp = require('jsonpath');
const data = require('./data.json');
const expected = ['id', 'name', 'email'];
expected.forEach(field => {
const result = jp.query(data, `$.users[*].${field}`);
console.log(`Field \${field}: \${result.length} values found`);
});
"

场景 3:CI/CD 中的结构验证#

validate-schema.js
const jp = require('jsonpath');
const fs = require('fs');
const schema = {
required: ['$.apiVersion', '$.info.title'],
types: {
'$.apiVersion': 'string',
'$.info.title': 'string',
'$.paths': 'object'
}
};
function validateJSONPath(data, schema) {
const errors = [];
for (const path of schema.required) {
const result = jp.query(data, path);
if (result.length === 0) {
errors.push(`Missing required path: ${path}`);
}
}
return errors;
}
const data = JSON.parse(fs.readFileSync('./openapi.json'));
const errors = validateJSONPath(data, schema);
if (errors.length > 0) {
console.error('验证失败:', errors);
process.exit(1);
}

场景 4:Postman 测试集成#

// Postman Pre-request Script
pm.test("API 响应包含所需字段", function () {
const response = pm.response.json();
// 使用 JSONPath 验证
const ids = jsonpath.query(response, '$.data.items[*].id');
pm.expect(ids.length).to.be.above(0);
const names = jsonpath.query(response, '$.data.items[*].name');
pm.expect(names.length).to.equal(ids.length);
});

场景 5:数据管道中的 JSONPath#

import json
from jsonpath_ng import parse
def extract_field(json_data, jsonpath_expr):
"""使用 JSONPath 从 JSON 中提取数据"""
expr = parse(jsonpath_expr)
return [match.value for match in expr.find(json_data)]
# 在数据管道中使用
def process_user_data(raw_data):
users = extract_field(raw_data, '$.users[*]')
emails = extract_field(raw_data, '$.users[*].email')
return list(zip(users, emails))

配置示例#

ESLint 自定义规则配置#

{
"rules": {
"json-path/valid-expression": ["error", {
"paths": ["$.apiVersion", "$.info.title"]
}]
}
}

VSCode JSONPath 片段#

{
"JSONPath - Root": {
"prefix": "jp-root",
"body": "$$.${1:path}",
"description": "JSONPath 根路径表达式"
},
"JSONPath - Filter": {
"prefix": "jp-filter",
"body": "$$[?(@.${1:field} ${2:operator} ${3:value})]",
"description": "JSONPath 过滤表达式"
}
}

总结#

将 JSONPath 测试集成到自动化测试、CI/CD 和数据管道中,可以确保数据提取逻辑的持续正确性。使用 星点网 xingdian.net 的在线 JSON 路径测试工具快速验证表达式,再将其纳入正式测试用例。

更多在线工具,请访问 星点网 xingdian.net 免费使用。

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

最后更新于 2026-06-01,距今已过 126 天

部分内容可能已过时

公告
🎉 已升级 2.0 版本,欢迎使用。
分类
标签
站点统计
文章
194
分类
23
标签
735
总字数
327,233
运行时长
0 天
最后活动
0 天前

目录