0

I have a JSON which contains 3 objects in a key => value manner. This JSON is wrapped into an Array. So now, I have an array which consists of JSON objects.

What i'm trying to do here is to remove one of the JSON's object (not the complete JSON element) from the array.

Any ideas to do the needful?

Sample JSON:

{
 'd_id' => '1',
 'name' => 'abc',
 'mapping' => 'xyz'
}

Sample Array

A = [{
 'd_id' => '1',
 'name' => 'abc',
 'mapping' => 'xyz'
},
{
 'd_id' => '2',
 'name' => 'abc',
 'mapping' => 'xyz'
},
{
 'd_id' => '3',
 'name' => 'abc',
 'mapping' => 'xyz'
}]

Here is what I have tried:

  1. Used an ArrayList instead of an Array to get the desired output.
  2. Used 'Remove' to clean up element in ArrayList.

powershell code:

$j_res = new-object collections.generic.list[object]

For ($i = 0; $i -lt 5; $i++){
$ret = ConvertFrom-Json "{}"
$ret | Add-Member -Name 'D_Id' -Value $i -MemberType NoteProperty
$ret | Add-Member -Name 'Name' -Value 'axz' -MemberType NoteProperty
$ret | Add-Member -Name 'Mapping' -Value 'byz' -MemberType NoteProperty
$j_res.Add($ret)
}
$j_res.Remove($j_res[0].Mapping)
Write-Host 'The  is required output is' $j_res

Expected:

A = [{
 'd_id' => '1',
 'name' => 'abc'
},
{
 'd_id' => '2',
 'name' => 'abc'
},
{
 'd_id' => '3',
 'name' => 'abc'
}]

Actual:

A = [{
 'd_id' => '1',
 'name' => 'abc',
 'mapping' => 'xyz'
},
{
 'd_id' => '2',
 'name' => 'abc',
 'mapping' => 'xyz'
},
{
 'd_id' => '3',
 'name' => 'abc',
 'mapping' => 'xyz'
}]
James Z
  • 12,209
  • 10
  • 24
  • 44
vibhor
  • 13
  • 2
  • Please look at this https://stackoverflow.com/questions/8820551/how-do-i-remove-a-specific-element-from-a-jsonarray, it has logic to achieve it – experimenter Apr 01 '19 at 09:45
  • @experimenter That Q&A is not related to PowerShell. –  Apr 01 '19 at 11:04
  • 1
    Instead of `$j_res.Remove($j_res[0].Mapping)` Use `$j_res | Select-Object D_Id,Name | ConvertTo-json` –  Apr 01 '19 at 11:04

1 Answers1

0

You are trying to remove element from the Array/List, but you should be looking at removing property of the PSObject inside the array.

$tmp = ConvertFrom-Json "[{`"id`" : 1,`"mapping`" : `"val`"},{`"id`" : 2,`"mapping`" : `"val`"},{`"id`" : 3,`"mapping`" : `"val`"}]"
foreach ($i in $tmp){
    $i.PSObject.Members.Remove("mapping")
}

ConvertTo-Json -InputObject $tmp -Depth 2 | Write-Host

Output:

{
  "value": [
    {
      "id":  1
    }, {
      "id":  2
    }, {
      "id":  3
    }
  ],
  "Count": 3
}
Chiranjib
  • 1,763
  • 2
  • 17
  • 29