我正在嘗試length從以下 JSON 檔案中洗掉值對:
{
"uuid": "6f74b1ba-0d7c-4c85-955b-2a4309f0e8df",
"records": {
"record1": [
{
"locale": "en_US",
"category": "alpha",
"contents": "My hovercraft is full of eels",
"length": 29
}
],
"record2": [
{
"locale": "cs_CZ",
"category": "alpha",
"contents": "Moje vzná?edlo je plné úho??",
"length": 28
}
]
}
}
即使length顯然找到了該屬性,它也不會被洗掉,因為輸出檔案與輸入檔案相同。
我正在使用以下代碼:
$infile = "C:\Temp\input.json"
$outfile = "C:\Temp\output.json"
$json = Get-Content $infile -Encoding UTF8 | ConvertFrom-Json
$records = $json.records
$records.PSObject.Properties | ForEach-Object {
if (($_.Value | Get-Member -Name "length")) {
Write-Host "length property found."
$_.Value.PSObject.Properties.Remove("length")
}
}
$json | ConvertTo-Json -Depth 3 | Out-File $outfile -Encoding UTF8
我究竟做錯了什么?
uj5u.com熱心網友回復:
record*屬性是陣列,因此您需要一個嵌套回圈來處理它們:
foreach( $property in $records.PSObject.Properties ) {
foreach( $recordItem in $property.Value ) {
if( $recordItem | Get-Member -Name 'length' ) {
$recordItem.PSObject.Properties.Remove( 'length' )
}
}
}
為了代碼清晰和性能,我用陳述句替換了ForEach-Object命令。foreach特別是在嵌套回圈中,foreach有助于提高清晰度,因為我們不再需要考慮自動$_變數的背景關系。此外,該foreach陳述句更快,因為它不涉及管道開銷。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487115.html
