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
OK, I think I found solution - it's not super clean but it's working
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:Note:
Using
-Raw
withGet-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.