1

I am getting some json data from a API, however I don't need most of this data. I am trying to remove some fields so that the when I save this data as a json file it isn't so large. I doesnt seem to be removing any of the fields I am trying to remove.

Code:

$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,
      "block": "Core Set",
      "booster": "@{default=}",
      "cards": "",
      "code": "2ED",
      ...
    },
    "2XM": {
      "baseSetSize": 332,
      "booster": "@{default=}",
      "cards": "",
      "code": "2XM",
      ...
    },
    ...
  }
}

1 Answer 1

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

The above code snippet should work. However, you can do all in a one step by calling the following (recursive) function 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
      }
    }
  }
}

# sample usage:

$Obj = ConvertFrom-Json $Response

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

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

(Please note that the RemoveProperty function contains some Write-Host in commented lines; originally used used for debugging purposes).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.