Home > Software design >  How to remove nested JSON object members
How to remove nested JSON object members

Time:06-07

I'm trying to remove the length value pair from the following JSON file:

{
    "uuid":  "6f74b1ba-0d7c-4c85-955b-2a4309f0e8df",
    "records":  {
                    "record1":  [
                                    {
                                        "locale":  "en_US",
                                        "category":  "alpha",
                                        "contents":  "My hovercraft is full of eels",
                                        "length":  29
                                    }
                                ],
                    "record2":  [
                                    {
                                        "locale":  "cs_CZ",
                                        "category":  "alpha",
                                        "contents":  "Moje vznášedlo je plné úhořů",
                                        "length":  28
                                    }
                                ]
                }
}

Even though the length property is apparently found, it's not deleted, because the output file is identical to the input file.

I'm using the following code:

$infile = "C:\Temp\input.json"
$outfile = "C:\Temp\output.json"

$json = Get-Content $infile -Encoding UTF8 | ConvertFrom-Json
$records = $json.records

$records.PSObject.Properties | ForEach-Object {
    if (($_.Value | Get-Member -Name "length")) {
        Write-Host "length property found."
        $_.Value.PSObject.Properties.Remove("length")
    }
}

$json | ConvertTo-Json -Depth 3 | Out-File $outfile -Encoding UTF8

What am I doing wrong?

CodePudding user response:

The record* properties are arrays, so you need a nested loop to process them:

foreach( $property in $records.PSObject.Properties ) {
    foreach( $recordItem in $property.Value ) {
       if( $recordItem | Get-Member -Name 'length' ) {
           $recordItem.PSObject.Properties.Remove( 'length' )
       }
   } 
}

For code clarity and performance I've replaced the ForEach-Object command by the foreach statement. Especially in nested loops, foreach helps to improve clarity as we no longer have to think about the context of the automatic $_ variable. Also the foreach statement is faster as it doesn't involve pipeline overhead.

  • Related