How to exclude non-valued object properties when converting to JSON in Powershell

后端 未结 4 1894
独厮守ぢ
独厮守ぢ 2020-12-31 10:40

I have a piece of code that works but I want to know if there is a better way to do it. I could not find anything related so far. Here are the facts:

  • I have an
4条回答
  •  鱼传尺愫
    2020-12-31 11:12

    Something like this?

    $object = New-Object PSObject
    
    Add-Member -InputObject $object -MemberType NoteProperty -Name TableName -Value "MyTable"
    Add-Member -InputObject $object -MemberType NoteProperty -Name Description -Value "Lorem ipsum dolor.."
    Add-Member -InputObject $object -MemberType NoteProperty -Name AppArea -Value "UserMgmt"
    Add-Member -InputObject $object -MemberType NoteProperty -Name InitialVersionCode -Value ""
    
    # Iterate over objects
    $object | ForEach-Object {
        # Get array of names of object properties that can be cast to boolean TRUE
        # PSObject.Properties - https://msdn.microsoft.com/en-us/library/system.management.automation.psobject.properties.aspx
        $NonEmptyProperties = $_.psobject.Properties | Where-Object {$_.Value} | Select-Object -ExpandProperty Name
    
        # Convert object to JSON with only non-empty properties
        $_ | Select-Object -Property $NonEmptyProperties | ConvertTo-Json
    }
    

    Result:

    {
        "TableName":  "MyTable",
        "Description":  "Lorem ipsum dolor..",
        "AppArea":  "UserMgmt"
    }
    

提交回复
热议问题