介绍
将JSON Diff集成到自动化工作流中,可以让数据变更的检测和响应更加高效。本文介绍多种集成方案。
集成场景
场景1:CI/CD Pipeline集成
yaml
# .github/workflows/json-diff-check.yml
name:
JSON
Config
Diff
Check
on:
pull_request:
paths:
['config/**/*.json']
jobs:
diff-check:
runs-on:
ubuntu-latest
steps:
- uses:
actions/checkout@v4
with:
fetch-depth:
2
- name:
Generate
JSON
diff
report
run:
|
git diff HEAD~1 -- '*.json' > json-diff-report.txt
- name:
Comment
diff
on
PR
uses:
actions/github-script@v7
with:
script:
|
const fs = require('fs');
const diff = fs.readFileSync('json-diff-report.txt', 'utf8');
github.rest.issues.createComment({
issue_number:
context.issue.number,
owner:
context.repo.owner,
repo:
context.repo.repo,
body:
`##
JSON配置变更\n\`\`\`diff\n${diff.slice(0,
30000
)}\n\`\`\``
});
场景2:Node.js自动化脚本
javascript
const fs = require('fs');
const { diff } = require('jsondiffpatch');
function checkConfigDiff(configDir) {
const baseline = JSON.parse(fs.readFileSync(`${configDir}/baseline.json`));
const current = JSON.parse(fs.readFileSync(`${configDir}/current.json`));
const delta = diff(baseline, current);
if (delta) {
console.log('配置变更检测到:');
console.log(JSON.stringify(delta, null, 2));
process.exit(1);
}
console.log('配置无变更');
}
checkConfigDiff('./config');
场景3:定时任务自动化对比
bash
#!/bin/bash
# 每天凌晨2点执行配置对比
0 2 * * * /usr/local/bin/json-diff-check.sh
# json-diff-check.sh
#!/bin/bash
curl -s https://api.example.com/v1/config > /tmp/config-current.json
node compare.js /tmp/config-baseline.json /tmp/config-current.json
场景4:Kubernetes配置审计
yaml
apiVersion:
batch/v1
kind:
CronJob
metadata:
name:
config-diff-audit
spec:
schedule:
"0 3 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name:
diff-check
image:
alpine:latest
command:
-
/bin/sh
-
-c
-
|
kubectl get configmap app-config -o json > /tmp/current.json
diff /tmp/baseline.json /tmp/current.json || echo "配置变更"
场景5:API回归测试集成
javascript
// 集成到测试框架中
describe('API Configuration Consistency', () => {
it('should not have unexpected JSON changes', async () => {
const response = await request(app).get('/api/config');
const baseline = await readBaseline('config.json');
const delta = jsondiffpatch.diff(baseline, response.body);
expect(delta).toBeUndefined();
});
});
配置示例
VSCode JSON Diff扩展配置
json
{
"json-diff.ignoreKeys": ["timestamp", "requestId"],
"json-diff.arrayComparison": "smart",
"json-diff.outputFormat": "tree"
}
Git配置JSON Diff工具
bash
# .gitattributes
*.json diff=json
# Git config
git config diff.json.textconv "python -m json.tool"
总结
将JSON差异比较集成到CI/CD、定时任务和审计系统中,可以让团队实时掌握数据变更动态。配合 星点网 xingdian.net 的在线JSON差异比较工具进行交互式分析,形成"自动化检测 + 人工确认"的完善流程。
更多在线工具,请访问 星点网 xingdian.net 免费使用。