Json 如何在power shell中从阵列中删除对象?
我正在尝试从数组中删除完整的对象,而不是该对象的成员。我无法找到删除该对象的方法。有太多的解决方案可用于删除该项。 有人能建议一种方法移除整个物体吗Json 如何在power shell中从阵列中删除对象?,json,windows,powershell,powershell-4.0,Json,Windows,Powershell,Powershell 4.0,我正在尝试从数组中删除完整的对象,而不是该对象的成员。我无法找到删除该对象的方法。有太多的解决方案可用于删除该项。 有人能建议一种方法移除整个物体吗 JSON Data: JSON data stored in the file. { "data": [ { "id": "Caption", "firstname": "Caption", "lastname": "test", "email": "test", "requ
JSON Data: JSON data stored in the file.
{
"data": [
{
"id": "Caption",
"firstname": "Caption",
"lastname": "test",
"email": "test",
"requester": "test",
"password": "test",
"incNumber": "test"
}
]
}
Code : I have written the following code to read the object from the array and store into variables to do the task.Once the task is completed I want to remove the object from the array.
$file = Get-Content '\path\to\file' -Raw | ConvertFrom-Json
$file.data | % {if($_.id -eq 'Caption'){
$1 = $_.id
Write-Host $1
###Here I want to remove the whole object related to the id
}}
我认为评论中的答案就是你想要的:
file.data=$file.data |?id-ne“标题”
为了对此进行一点解释,它使用了?
,这实际上是Where Object
cmdlet的别名(可选名称),当您希望根据某些条件筛选集合时,可以使用该别名(如果您熟悉的话,与SQL中的Where
语句非常类似)
以上答案是一个简短的版本,您也可以看到:
$file = Get-Content '\path\to\file' -Raw | ConvertFrom-Json
$Result = $file.data | Where-Object {$_.id -ne 'Caption'}
它将ScriptBlock
{}
传递到Where Object cmdlet,并使用$\UUcode>表示管道中的每个项目,然后使用-ne
作为非相等比较运算符,查看该对象的ID
属性是否与字符串标题
不匹配。如果该值被评估为true,则它允许该项通过管道,在上面的示例中,这意味着它将在$Result
变量中结束。如果该语句的计算结果为false,则它将丢弃集合中的该项,并转到下一项。$file.data=$file.data |?id-ne“Caption”
感谢您的解释。我能够读取对象并在接下来的步骤中使用数据。我想要的是当它被使用并处理完成时,我想从列表中删除此对象。您能告诉我一种从列表中删除它的方法吗?为什么需要这样做?之后如何处理筛选后的列表?您可以使用where cmdlet在一个变量中创建筛选列表,同时以当前的方式处理它们。这有帮助吗?这是一个临时位置,我正试图在这里保存数据一段时间,并在收到下一个请求时使用它。请求发出后,我想清除数组列表,因为不再需要它,因此没有存储它的意义。请让我知道此过程是否有任何错误。然后在最后将其设置为$null?