I have a piece of code that works, but I want to know if there is a better way to do this. So far, I could not find anything related. Here are the facts:
- I have an object with n properties.
- I want to convert this object to JSON using (ConvertTo-Json).
- I do not want to include in JSON those properties of the object that are not evaluated.
Building an object (not very important):
$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 ""
The line where I need improvements (to filter out unvalued properties and not include them in JSON)
What this line provides:
Results: { "TableName": "MyTable", "Description": "Lorem ipsum dolor..", "AppArea": "UserMgmt", "InitialVersion": null } What I want to obtain: { "TableName": "MyTable", "Description": "Lorem ipsum dolor..", "AppArea": "UserMgmt" }
That I tried and works, but I donβt like it, because I have much more properties for processing:
$JSON = New-Object PSObject if ($object.TableName){ Add-Member -InputObject $JSON -MemberType NoteProperty -Name TableName -Value $object.TableName } if ($object.Description){ Add-Member -InputObject $JSON -MemberType NoteProperty -Name Description -Value $object.Description } if ($object.AppArea){ Add-Member -InputObject $JSON -MemberType NoteProperty -Name AppArea -Value $object.AppArea } if ($object.InitialVersionCode){ Add-Member -InputObject $JSON -MemberType NoteProperty -Name InitialVersionCode -Value $object.InitialVersionCode } $JSON | ConvertTo-Json
source share