gpt4 book ai didi

json - Powershell:比较对象不比较嵌套对象

转载 作者:行者123 更新时间:2023-12-04 19:35:24 25 4
gpt4 key购买 nike

或者我是如何不再担心并学会爱上弦乐收藏的

给定以下两个 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>

有没有更简单的方法来深度比较两个对象?

最佳答案

不知道是不是更好,但是:

$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" <=

关于json - Powershell:比较对象不比较嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24790099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com