symptom implies比object with the 100 property is part of an array,所以你有两个 Select :
如果只有one个对象的.item
属性你感兴趣,use its index;如果数组只有一个元素,使用[0]
:
$fromJson[0].item
# To then access the nested .items property:
$fromJson[0].item.items
若要从数组中的all个对象获取.item
个属性值,请使用:
# Fast, but always returns an *array-like* object.
$fromJson.ForEach('item')
# To then access the nested .items property:
$fromJson.ForEach('item').items
# ---
# Slower pipeline alternative, behaves like
# member-access enumeration.
$fromJson | ForEach-Object item
# To then access the nested .items property:
$fromJson | ForEach-Object item | ForEach-Object items
# OR, with the built-in % alias
$fromJson | % item | % items
# OR - given that member-access enumeration does work with .items:
($fromJson | ForEach-Object).items
注:
嵌套的.items
属性本身是数组值的,它只显示System.Object[]
,即只显示type条信息,而不是实际值,这一事实只是嵌套的结果formatting artifact,如以下嵌套[pscustomobject]
的输出所示:
# -> item : @{items=System.Object[]}
[pscustomobject] @{ item = [pscustomobject] @{ items = 1..3 } }
Background information:
如果ConvertFrom-Json
调用输出的[pscustomobject]
对象图碰巧是array,则try 访问数组上不是数组对象本身的属性的属性会导致member-access enumeration,即属性访问自动应用于数组的each element个,并返回一个值array.
这意味着,即使对象恰好是一个single-element数组(您可能不知道),您仍然可以normally直接访问该数组上感兴趣的属性;例如:
# Effectively the same as:
# @([pscustomobject] @{ foo = 1 })[0].foo
@([pscustomobject] @{ foo = 1 }).foo # -> 1
然而,Item
恰好是System.Array
个实例中的parameterized property个实例的名称,它位于indexed access的下面.[1]
因此,它是takes precedence over member-access enumeration,并且--因为该属性需要argument(位置索引),但没有被赋予--PowerShell打印参数化属性的definition(如果您只调用其名称,而不调用参数列表,则打印method的定义的方式相同;例如,(42).ToString
).
这是你看到的症状,你可以很容易地复制它如下:
# !! Prints the definition of the array's parameterized .Item property
# !! instead of returning the only element's .item property value.
@([pscustomobject] @{ item = 'foo' }).item
如上所示,intrinsic .ForEach()
method提供了一种避免这种名称冲突的简单方法,因为它显式地访问给定名称on each element的属性.
但是,请注意,与成员访问枚举不同的是,结果是always个数组(类似集合),即使只有one个值.
另一种方法是将pipeline与ForEach-Object
cmdlet一起使用,如上所示;虽然速度较慢,但它表现出与成员访问枚举相同的输出行为.
[1]严格地说,此属性是显式IList
接口实现的一部分,但PowerShell甚至将显式实现的Faces的成员表面化为给定类型的直接成员.
[2]成员访问枚举按原样返回单个值,并将多个值作为常规PowerShell数组返回,即类型化的[object[]]
..ForEach()
方法(以及.Where()
方法)always返回一个类似数组的[System.Collections.ObjectModel.Collection[psobject]]
实例.