Search code examples
jsonpowershellpowershell-core

Exclude the JSON property only if it exists - Powershell


I have two different JSONs and I would like to remove streets from the JSON object if only it exists under Address which is an array. I am trying to do this in powershell. I can get my script working and remove the streets but I only want to run the exclude line of command if the address has the streets property.

{
    "Customer": [{
        "id": "123"
    }],
    "address": [{
            "$type": "Home",
            "name": "Houston",
            "streets": [{
                "name": "Union",
                "postalCode": "10"
            }]
        },
        {
            "$type": "Office",
            "name": "Hawai",
            "streets": [{
                "name": "Rock",
                "postalCode": "11"
            }]
        }
    ]
}

2nd JSON - Do not want to run the exclude line for 2nd JSON because there are no streets

{
    "Customer": [{
        "id": "123"
    }],
    "address": [{
            "$type": "Home",
            "name": "Houston"
        },
        {
            "$type": "Office",
            "name": "Hawai"
        }
    ]
}

Powershell script

$FileContent = Get-Content -Path "Test.json" -Raw | ConvertFrom-Json
#Only want to run for address objects that contains streets
$FileContent.address = $FileContent.address | Select-Object * -ExcludeProperty streets #Only run for 1st json and not for 2nd json
$FileContent | ConvertTo-Json


Solution

  • If you want to execute the code only if the address has the member streets you can test for just that:

    if (
        ($FileContent.address | Get-Member -MemberType NoteProperty -Name "streets") -ne $null
    ){
        $FileContent.address = $FileContent.address | Select-Object * -ExcludeProperty streets
    }