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

后端 未结 4 1909
独厮守ぢ
独厮守ぢ 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 10:58

    beatcracker's helpful answer offers an effective solution; let me complement it with a streamlined version that takes advantage of PSv4+ features:

    # Sample input object
    $object = [pscustomobject] @{
      TableName = 'MyTable'
      Description = 'Lorem ipsum dolor...'
      AppArea = 'UserMgmt'
      InitialVersionCode = $null
    }
    
    # Start with the list of candidate properties.
    # For simplicity we target *all* properties of input object $obj
    # but you could start with an explicit list as wellL
    #   $candidateProps = 'TableName', 'Description', 'AppArea', 'InitialVersionCode'
    $candidateProps = $object.psobject.properties.Name
    
    # Create the filtered list of those properties whose value is non-$null
    # The .Where() method is a PSv4+ feature.
    $nonNullProps = $candidateProps.Where({ $null -ne $object.$_ })
    
    # Extract the list of non-null properties directly from the input object
    # and convert to JSON.
    $object | Select-Object $nonNullProps | ConvertTo-Json
    

提交回复
热议问题