我正在使用 deepDiff 以结构方式显示两个 json 之间的差异,到目前为止一切顺利。但我想强调解析的 json 内容中的差异。它实际上不起作用。我该如何解决这个问题?
求差函数:
compareFiles() {
if (this.file1Content && this.file2Content) {
const differences = deepDiff.diff(this.file1Content.apis, this.file2Content.apis);
if (differences) {
this.comparisonResult = this.formatDifferences(differences);
const filteredDifferences = differences.filter(diff => diff.path && !diff.path.some(p => p.key === 'index' && p.ignoreOrder));
this.comparisonResult2 = filteredDifferences ? JSON.stringify(filteredDifferences, null, 2) : 'No differences found.';
this.highlightedFile1Content = this.getHighlights(this.file1Content, differences);
this.highlightedFile2Content = this.getHighlights(this.file2Content, differences);
}
}
}
获取亮点功能:
getHighlights(jsonObject: any, differences: deepDiff.Diff<any, any>[]): string {
try {
let jsonString = JSON.stringify(jsonObject, null, 2);
const lines = jsonString.split('\n');
differences.forEach(diff => {
if (diff.path && diff.path.length > 0) {
let valueToHighlight: string | undefined;
let pathString: string = '';
let indicesString: string = '';
const indices = diff.path.filter(segment => typeof segment === 'number');
indicesString = indices.join(', ');
pathString = diff.path.map(segment =>
typeof segment === 'number' ? `[${segment}]` : `.${segment}`
).join('');
switch (diff.kind) {
case 'E':
valueToHighlight = JSON.stringify(diff.rhs);
break;
case 'N':
valueToHighlight = JSON.stringify(diff.rhs);
break;
case 'D':
valueToHighlight = JSON.stringify(diff.lhs);
break;
case 'A':
break;
}
if (valueToHighlight) {
const regexPath = new RegExp(`("${diff.path[diff.path.length - 1]}":\\s*(${valueToHighlight}))`);
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(regexPath);
if (match) {
const matchedValue = match[2];
lines[i] = lines[i].replace(matchedValue, `<span class="highlight">${matchedValue} DIFFERENCE FOUND! Indices: ${indicesString}</span>`);
}
}
}
}
});
return lines.join('\n');
} catch (e) {
console.error("Error in formatContent:", e);
return JSON.stringify(jsonObject, null, 2);
}
}
我尝试在上面运行