比较 json 个文件但忽略值
Compare json files but ignore values
我想比较两个 json 文件并报告差异,但我只对键感兴趣,不对 值感兴趣。因此,例如以下两个文件之间的“json-diff”(当然它们要复杂得多):
{
"http": {
"https": true,
"swagger": {
"enabled": false
},
"scalingFactors": [0.1, 0.2]
}
}
{
"http": {
"https": true,
"swagger": {
"enabled": true
},
"scalingFactors": [0.1, 0.1],
"test": true
}
}
应该报告缺少密钥:
http.test
但是
不应报告以下键具有不同的值:
http.swagger.enabled
http.scalingFactors
我查看了 jq
工具,但我不确定如何忽略值。
忽略与数组有关的潜在复杂性,查看标量路径集的“对称差异”是有意义的。作为起点,您可以考虑:
jq -c '
[paths(scalars)] as $f1
| [input | paths(scalars)] as $f2
| ($f1 - $f2) + ($f2 - $f1)' file1.json file2.json
您可能希望将路径字符串化,但话又说回来,如果到字符串的映射是不可逆的,那么避免这样做可能是明智的。
如果存在数组,您可能希望在忽略数组索引的同时比较路径:
def p: [paths(scalars) | map(select(type=="string"))] | unique;
p as $f1
| (input | p) as $f2
| ($f1 - $f2) + ($f2 - $f1)
| .[]
最后一行确保结果是一个(可能为空的)流,关键是这使得检查 return 代码以确定是否检测到任何差异变得容易:只需使用 -e command-line 选项。如果没有差异,那么 return 代码将为 4.
检查流是否为空的一种方法是使用 -4
我想比较两个 json 文件并报告差异,但我只对键感兴趣,不对 值感兴趣。因此,例如以下两个文件之间的“json-diff”(当然它们要复杂得多):
{
"http": {
"https": true,
"swagger": {
"enabled": false
},
"scalingFactors": [0.1, 0.2]
}
}
{
"http": {
"https": true,
"swagger": {
"enabled": true
},
"scalingFactors": [0.1, 0.1],
"test": true
}
}
应该报告缺少密钥:
http.test
但是
不应报告以下键具有不同的值:
http.swagger.enabled
http.scalingFactors
我查看了 jq
工具,但我不确定如何忽略值。
忽略与数组有关的潜在复杂性,查看标量路径集的“对称差异”是有意义的。作为起点,您可以考虑:
jq -c '
[paths(scalars)] as $f1
| [input | paths(scalars)] as $f2
| ($f1 - $f2) + ($f2 - $f1)' file1.json file2.json
您可能希望将路径字符串化,但话又说回来,如果到字符串的映射是不可逆的,那么避免这样做可能是明智的。
如果存在数组,您可能希望在忽略数组索引的同时比较路径:
def p: [paths(scalars) | map(select(type=="string"))] | unique;
p as $f1
| (input | p) as $f2
| ($f1 - $f2) + ($f2 - $f1)
| .[]
最后一行确保结果是一个(可能为空的)流,关键是这使得检查 return 代码以确定是否检测到任何差异变得容易:只需使用 -e command-line 选项。如果没有差异,那么 return 代码将为 4.
检查流是否为空的一种方法是使用 -4