PowerShell通过嵌套json循环并删除属性

问题描述

我从API获取了一些json数据,但是我不需要这些数据中的大多数。我试图删除一些字段,以便当我将这些数据另存为json文件时不会太大。我似乎并未删除我要删除的任何字段。

代码

$Response = Invoke-RestMethod -Uri "https://mtgjson.com/api/v5/AllPrintings.json" -Method GET
$Obj = ConvertFrom-Json $Response

$Obj.PSObject.Properties.Remove('booster')
$Obj.PSObject.Properties.Remove('cards')

$Obj | ConvertTo-Json | Out-File ./All-Sets-Data.json -Force

Json:

{
  "data": {
    "10E": {
      "baseSetSize": 383,"block": "Core Set","booster": "@{default=}","cards": "","code": "10E",...
    },"2ED": {
      "baseSetSize": 302,"code": "2ED","2XM": {
      "baseSetSize": 332,"code": "2XM",...
  }
}

解决方法

$Obj.data.'10E'.PSObject.Properties.Remove('booster')
$Obj.data.'10E'.PSObject.Properties.Remove('cards')
$Obj.data.'2ED'.PSObject.Properties.Remove('booster')
# and so on

上面的代码段应该起作用。但是,您可以通过调用以下(递归)函数RemoveProperty一步完成所有工作:

Function RemoveProperty {
  param (
    # A PSCustomObject
    [Parameter( Mandatory,ValueFromPipeline )] $Object,# A list of property names to remove
    [Parameter( Mandatory )] [string[]]$PropList,# recurse?
    [Parameter()] [Switch]$Recurse
  )
  # Write-Host $Object  -ForegroundColor Cyan
  foreach ( $Prop in $PropList ) {
    $Object.PSObject.Properties.Remove($prop)
  }
  # Write-Host $Object  -ForegroundColor Green
  if ( $Recurse.IsPresent ) {
    foreach ($ObjValue in $Object.PSObject.Properties.Value) {
      # Write-Host $ObjValue  -ForegroundColor Yellow
      if ( $ObjValue.GetType().Name -eq 'PSCustomObject' ) {
        $ObjValue | RemoveProperty -PropList $PropList -Recurse
      }
    }
  }
}

#个示例用法:

$Obj = ConvertFrom-Json $Response

RemoveProperty -Object $Obj -PropList 'booster','cards' -Recurse

$Obj | ConvertTo-Json | Out-File ./All-Sets-Data.json -Force

(请注意,RemoveProperty函数在注释行中包含一些Write-Host;最初用于调试目的)。