仅当JSON属性存在时才排除它-Powershell [英] Exclude the JSON property only if it exists - Powershell

查看:76
本文介绍了仅当JSON属性存在时才排除它-Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种不同的JSON,如果仅在Address(它是一个数组)下存在,我想从JSON对象中删除街道.我正在尝试在Powershell中执行此操作.我可以使脚本正常工作并删除街道,但是如果地址具有streets属性,我只想运行命令的排除行.

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"
            }]
        }
    ]
}

第二个JSON-因为没有街道,所以不想为第二个JSON运行排除行

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脚本

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

推荐答案

如果只想执行代码ifaddress具有member streets,则可以测试一下:

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
}

这篇关于仅当JSON属性存在时才排除它-Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆