Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove nested JSON object members

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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?

>Solution :

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 replace ForEach-Object by foreach statement. Especially in nested loops, foreach helps to improve clarity as we no longer have to think about the context of the $_ variable. Also the foreach statement is faster as it doesn’t involve pipeline overhead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading