我正在尝试创建一个函数来循环json文件,并根据特定条件满足,希望将json键的值添加到数组中,但无法完成相同的任务。
以下是联合选举委员会:
$a1 = [ {
"name": "sachin",
"surname": "",
},
{
"name": "Rajesh",
"surname": "Mehta"
}
]我创建的函数如下:
function addingkeyval
{
param ($key,
[Array]$tobeaddedarr)
$a1 | Select-Object -Property name,surname | ForEach-Object {
if($_.$key-eq "")
{
}
else
{
$tobeaddedarr +=$_.$key+","
}
}
}当我在这个函数中使用以下语句时:
$surnamearr = @()
addingkeyval -key surname -tobeaddedarr $surnamearr
i want the output in the array $surnamearr as below
("Mehta")不知何故,我无法在数组中增加价值,有人能帮助我实现同样的目标吗?
发布于 2020-05-05 11:33:28
$surnamearr = ([string[]] (ConvertFrom-Json $a1).surname) -ne ''ConvertFrom-Json $a1将JSON数组转换为PowerShell自定义对象数组(键入[pscustomobject]).)
(...).surname使用member-access enumeration.提取结果数组中对象的所有.surname属性的值。
[string[]]确保将结果作为数组处理(如果$a1中的数组碰巧只包含一个元素,则不会处理),并显式地将其转换为字符串,因此通过-ne ''过滤非空值也适用于不具有.surname属性的输入对象。-ne ''过滤掉结果数组中的所有空字符串元素(使用数组作为LHS,比较运算符(如-ne )充当数组筛选器,而不是返回布尔值)。结果是,$surnamearr是一个包含所有非空.surname属性值的数组。
至于,你尝试过
$tobeaddedarr +=$_.$key+","
该语句隐式地创建一个新数组,与调用者通过$tobeaddedarr参数变量传递的数组引用不同-因此,调用方从未看到更改。
通常不能传递要附加到就地的数组,因为数组相对于元素的数量是不可变的。
虽然您可以传递一个类似数组的可变结构(比如[System.Collections.Generic.List[object]]实例,您可以用它的.Add()方法附加到它),但是在函数中构建一个新数组并输出它要简单得多。
因此,您可以将您的函数编写为:
function get-keyval
{
param ($key)
# Implicitly output the elements of the array output by using this command.
([string[]] (ConvertFrom-Json $key).surname) -ne ''
}
$surnamearr = get-keyval surname注意:
默认情况下,
- While it is possible to output an array _as a whole_, via the unary form of `,`, the array-construction operator ( `, (([string[]] (ConvertFrom-Json $a1).surname) -ne '')`), which improves performance, the problem is that the caller may not expect this behavior, especially not in a _pipeline_.如果您在一个变量(如此处的
[object[]]数组中的单个输出对象;但是,请注意,单个输出对象按原样返回,即不包装在数组中。- You can wrap `@(...)` around the function call to ensure that you _always_ get an array
- Alternatively, type-constrain the receiving variable: `[array] $surnamearr = ...`, which also creates an `[object[]]` array, or something like `[string[]] $surnamearr = ...`, which creates a strongly typed string array.https://stackoverflow.com/questions/61610940
复制相似问题