或者我是如何停止担心并学会喜欢字符串集的
给出以下两个json字符串:
$jsonString1 = '{ "baz": "quuz", "cow": [ "moo", "CUD" ], "foo": "bar" }'
$jsonstring2 = '{ "baz": "quuz", "cow": [ "moo", "GRASS" ], "foo": "bar" }'
我希望得到它们所代表的对象的差异
<# First attempt: Convert each to an object, then compare normally #>
function Compare-Json {
<# Make powershell objects from each string #>
$obj1 = $jsonString1 | ConvertFrom-Json
$obj2 = $jsonstring2 | ConvertFrom-Json
Compare-Object $obj1 $obj2
}
PS E:\temp> Compare-Json
PS E:\temp>
是的,根本就没有输出。
目前的解决方法是将json转换为对象,返回字符串,然后拆分字符串,最后比较每个集合
function Compare-Json {
<# Convert to pretty json, then split to make a string array #>
$obj1 = $($jsonString1 | ConvertFrom-Json | ConvertTo-Json) -split ([Environment]::NewLine)
$obj2 = $($jsonstring2 | ConvertFrom-Json | ConvertTo-Json) -split ([Environment]::NewLine)
Compare-Object $obj1 $obj2
}
PS E:\temp> Compare-Json
InputObject SideIndicator
----------- -------------
"GRASS" =>
"CUD" <=
PS E:\temp>
是否有更简单的方法来深度比较两个对象?
答案 0 :(得分:0)
不知道它是否更好,但是:
$jsonString1 = '{ "baz": "quuz", "cow": [ "moo", "CUD" ], "foo": "bar" }'
$jsonstring2 = '{ "baz": "quuz", "cow": [ "moo", "GRASS" ], "foo": "bar" }'
compare $jsonString1.split(',:[]{}') $jsonString2.split(',:[]{}')
InputObject SideIndicator
----------- -------------
"GRASS" =>
"CUD" <=