skip to Main Content

I working with JSON file:

{
    "Job":  "abc",
    "Tasks":  [
                  {
                      "Task":  1
                  },
                  {
                      "Task":  2
                  }
              ]
}

and in some cases I have to remove all tasks and then my output JSON file looks like this:

{
    "Job":  "abc",
    "Tasks": null
}

PowerShell code which I’m using to remove tasks below:

$Job = Get-Content -Path '.Job.json'|ConvertFrom-Json
$Tasks = $Job.Tasks
$Tasks = $Tasks|Where-Object {$_.Task -ne 1}
$Tasks = $Tasks|Where-Object {$_.Task -ne 2}
$Job|ConvertTo-JSON -Depth 2|Out-File -Path '.Job.json'

This JSON file is used by other tools and this null field causing issues.
I have tried to use Array and ArrayList but as far as I found PowerShell doesn’t support indexOf() method so I don’t know which item has to be removed.

2

Answers


  1. Chosen as BEST ANSWER

    OK, I think I found solution - it's not super clean but it's working

        $Job = Get-Content -Path '.Job.json'|ConvertFrom-Json
        $Job.Tasks = $Job.Tasks|Where-Object {$_.Task -ne 1}
        $Job.Tasks = $Job.Tasks|Where-Object {$_.Task -ne 2}
        if(-not ($Job.Tasks)){
            $Job.Tasks = @()
        }
        else {
            $Job.Tasks = , $Job.Tasks
        }
        $Job|ConvertTo-Json -Depth 2|Out-File -FilePath '.Job.json'
    

  2. Use @(...), the array-subexpression operator, whose purpose is exactly to ensure that a pipeline’s collected output is unconditionally made an array – even if there is no or just one output object:

    $job = Get-Content -Raw .Job.json | ConvertFrom-Json
    
    # Use @(...) to ensure the output becomes an array.
    $job.Tasks = @($job.Tasks | Where-Object { $_.Task -notin 1, 2 })
    
    $job | ConvertTo-Json -Depth 2 | Out-File .Job.json
    

    Note:

    • Using -Raw with Get-Content is more efficient: it reads the entire file into a single string.

    • A single Where-Object call is used, using a single logical operation based on -notin operator.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search