0

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.

  • I'm not sure what you are trying to do? Are you trying to just replace the "_" in the field name? aka instead of _filterOrder you want filterOrder? And what do the empty strings "" have to do with it? and Which version of powershell are you using? – Shadowzee Nov 23 '17 at 03:39
  • I thought I had explained the issue and what I wanted to do. My apologies if I was unclear. Yes I do want to remove the pre-pended "_" from just the key names before I convert the object to JSON. I did find a method to do the renaming, however, it doesn't differentiate between a key "name" or the key "value". It just removed ALL "_" it finds. So, if the key values have an "_" anywhere in a string type, that would be removed also. – JackHubbard Nov 24 '17 at 15:42
  • Have you tried using a dictionary? You won't need to create the class with '_' in the field name, it can be converted to json and is pretty flexible. @{"filterorder" = 0; property = ""; "values" = @(1,2,3); "value"= @{"one"= 1}} – Shadowzee Nov 27 '17 at 04:40

0 Answers0