Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Json object manipulation

I am hitting a Rest API and collected a gnarly block of Json. I'm running convertfrom-json on that to get a powershell object which I would like to manipulate. Essentially I need to prune a number of field/values.

Its no issue to 'get' the fields I want to remove from the object as I can just drill down to the field and collect the value thats easy, where I am stuck is how to trim off that field from the posh object. Would appreciate any assistance. Thanks.

Example:

$sample_json = @"
{
    "fields": {
        "field_one": 1,
        "field_two": 2,
        "field_three": "three",
        "field_four": "remove_me",
        "field_five": 5
    }
}
"@
Clear-Host 
$json_object = ConvertFrom-Json -InputObject $sample_json
$json_object

Gives:

fields                                                                            
------                                                                            
@{field_one=1; field_two=2; field_three=three; field_four=remove_me; field_five=5}

So the question is how can I remove "field_four" key, and it's value, from $json_object ? Apologies if this is crazy simple; I'm a bit out of touch with Powershell these last few years.

like image 293
Indrid Avatar asked May 30 '26 02:05

Indrid


2 Answers

You can remove "field_four" with the Remove method from PSObject.Properties:

$json_object.fields.PSObject.Properties.Remove("field_four")
like image 175
Matt Avatar answered Jun 01 '26 14:06

Matt


Use the following statement

$json_object.fields.PSObject.Properties.Remove("field_four")
like image 43
Peter Schneider Avatar answered Jun 01 '26 14:06

Peter Schneider