你可以尝试使用包https://github.com/coduo/php-matcher
示例:这两个对象应该被认为是相等的,因为它们具有相同的结构:索引变量和标签数组。
您可以像这样创建“php-matcher 模式”:
{
"index": "@integer@",
"tags": "@array@.repeat(\"@string@\")"
}
然后你将你的 JSON 与这个模式进行匹配。如果您有 2 个 JSON 并且都匹配此模式,那么根据您上面对相等的定义,这意味着它们是 “相等”。
请在“php-matcher 沙箱”中查看您提供的示例 JSON 的结果:
Example 1 in sandbox
Example 2 in sandbox
此外,当模式与值不匹配时,您可以使用包 https://github.com/sebastianbergmann/diff(如果您有 phpunit,您应该已经拥有)生成差异。
例如:
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
...
$valueToCheck = '{
"foo": 0,
"bar": {"one": 1, "two": "2"}
}';
$expectedValuePattern = '{
"foo": "@integer@",
"bar": {"one": 1, "two": 2}
}';
if (!$matcher->match($valueToCheck, $expectedValuePattern)) {
$differ = new Differ(
new UnifiedDiffOutputBuilder(
"Json value is not matching expected format:\n",
true
)
);
$diffOutput = $differ->diff(
\json_encode(\json_decode($expectedValuePattern, true), JSON_PRETTY_PRINT),
\json_encode(\json_decode($valueToCheck, true), JSON_PRETTY_PRINT)
);
var_dump(
$diffOutput
. "\n".$matcher->getError()."\n"
);
} else {
var_dump('OK');
}
它会打印出来:
Json value is not matching expected format:
@@ -1,7 +1,7 @@
{
- "foo": "@integer@",
+ "foo": 0,
"bar": {
"one": 1,
- "two": 2
+ "two": "2"
}
}
带有 diff 的消息特别有助于较大的 JSON 快速查看哪个元素不匹配。
在该软件包的 README 中查看更多使用方式 - 特别是:
https://github.com/coduo/php-matcher#json-matching
https://github.com/coduo/php-matcher#json-matching-with-unbounded-arrays-and-objects
这个包非常适合用于自动测试(例如:phpunit)来断言来自 API 响应的 JSON 是否正确等 - 考虑到在集成测试中通常有许多 id、uuid、datetime 等在每个测试中都会发生变化执行 - 如数据库生成的 id 等。
希望对你有帮助:)