【发布时间】:2019-08-22 10:33:41
【问题描述】:
我有一个 JSON,它以键 => 值的方式包含 3 个对象。这个 JSON 被包装到一个数组中。所以现在,我有一个由 JSON 对象组成的数组。
我在这里要做的是从数组中删除一个 JSON 对象(不是完整的 JSON 元素)。
有什么想法可以满足需要吗?
示例 JSON:
{
'd_id' => '1',
'name' => 'abc',
'mapping' => 'xyz'
}
样本数组
A = [{
'd_id' => '1',
'name' => 'abc',
'mapping' => 'xyz'
},
{
'd_id' => '2',
'name' => 'abc',
'mapping' => 'xyz'
},
{
'd_id' => '3',
'name' => 'abc',
'mapping' => 'xyz'
}]
这是我尝试过的:
- 使用 ArrayList 而不是 Array 来获得所需的输出。
- 使用“删除”清理 ArrayList 中的元素。
powershell 代码:
$j_res = new-object collections.generic.list[object]
For ($i = 0; $i -lt 5; $i++){
$ret = ConvertFrom-Json "{}"
$ret | Add-Member -Name 'D_Id' -Value $i -MemberType NoteProperty
$ret | Add-Member -Name 'Name' -Value 'axz' -MemberType NoteProperty
$ret | Add-Member -Name 'Mapping' -Value 'byz' -MemberType NoteProperty
$j_res.Add($ret)
}
$j_res.Remove($j_res[0].Mapping)
Write-Host 'The is required output is' $j_res
预期:
A = [{
'd_id' => '1',
'name' => 'abc'
},
{
'd_id' => '2',
'name' => 'abc'
},
{
'd_id' => '3',
'name' => 'abc'
}]
实际:
A = [{
'd_id' => '1',
'name' => 'abc',
'mapping' => 'xyz'
},
{
'd_id' => '2',
'name' => 'abc',
'mapping' => 'xyz'
},
{
'd_id' => '3',
'name' => 'abc',
'mapping' => 'xyz'
}]
【问题讨论】:
-
请看这个stackoverflow.com/questions/8820551/…,它有实现它的逻辑
-
@experimenter Q&A 与 PowerShell 无关。
-
用
$j_res.Remove($j_res[0].Mapping)代替$j_res | Select-Object D_Id,Name | ConvertTo-json
标签: powershell