I have a project in PowerShell where I created a custom type using the "Add-Type". I wanted to use classes, but I'm limited to the PowerShell version on the system I have to use.
This object gets converted to JSON and is sent out using a REST API. To avoid some naming issues I ended up pre-pending ""s to the field names. I want to remove those before it is sent to the API. I thought it would be simple to do the rename, and it was, but then I realized the method I used for the rename would potentially cause issues if I renamed everything in the JSON object by removing anything with the "".
Here is the custom type:
Add-Type -typedef @"
public class SearchFilter
{
public int _filterOrder;
public string _property;
public string _direction;
public string _value;
public string[] _values;
public string _operator;
public SearchFilter()
{
_filterOrder = 0;
_property = "";
_direction = "";
_value = "";
_values = new string[0];
_operator = "";
}
}
"@
Using just a string REPLACE method I'll get this:
{
"filterOrder": 0,
"property": "name",
"direction": "ASC",
"value": "value",
"values": [],
"operator": "Contains"
}
instead of this:
{
"filterOrder": 0,
"property": "name",
"direction": "ASC",
"value": "_value_",
"values": [],
"operator": "Contains"
}
Here is the method I'm using:
# Create search filter object
$searchFilter = New-Object -TypeName "SearchFilter"
# Convert search filter to REST API JSON format
$apiPostBody = ConvertTo-Json -InputObject $searchFilter
# Remove all "_"
$apiPostBody = $apiPostBody .Replace("_","")
I have checked the methods available from PSObject, but I'm just not sure of the syntax. If possible I'd like to change the existing object before converting to JSON as opposed to having to create a CLONE or iterate through the JSON value.