本文介绍了格式化由Invoke-RestMethod或ConvertFrom-Json返回的[pscustomobject]实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当我打印json对象的属性时,我得到一个输出像这样:
$ b $ pre>写输出JSON.Object
$ b $ Object1:@ {key1 = property;键2 =属性; KEY3 =属性; key4 = property}
Object2:@ {key1 = property;键2 =属性; KEY3 =属性; key4 = property}
Object3:@ {key1 = property;键2 =属性; KEY3 =属性; key4 = property}
Object4:@ {key1 = property;键2 =属性; KEY3 =属性; key4 = property}

我想看到的输出是这样的:

名称key1 key2 key3 key4 
----- ---- ---- ---- ----
Object1属性属性属性
Object2属性属性属性
Object3属性属性属性

另外,是否可以避免显示特定的键和它的属性?

示例:

名称key1 key2 key4 #←不显示key3  
----- ---- ---- ----
Object1属性属性
Object2属性属性
Object3属性property property


解决方案

您需要将父键名添加为名称嵌套对象:

  $ json.Object | ForEach-Object {
foreach($ _。PSObject.Properties中的$ p){
$ p.Value | Select-Object @ {n ='Name'; e = {$ p.Name}},*
}
}

请注意,PowerShell将默认呈现列表形式的输出,因为您的对象具有超过4个属性。通过 Format-List -AutoSize 来获取表格输出。


I am trying to create a table from a JSON file I am receiving from a RESTful API.

When I print the property of the json object I get an output like this:

PS> Write-Output JSON.Object

Object1           : @{key1=property; key2=property; key3=property; key4=property}
Object2           : @{key1=property; key2=property; key3=property; key4=property}
Object3           : @{key1=property; key2=property; key3=property; key4=property}
Object4           : @{key1=property; key2=property; key3=property; key4=property}

The output I would like to see is this:

Name              key1        key2        key3        key4
-----             ----        ----        ----        ----
Object1           property    property    property    property
Object2           property    property    property    property
Object3           property    property    property    property

In addition, is it possible to avoid displaying a specific key and it's properties?

Example:

Name              key1        key2        key4      # ← Not displaying key3
-----             ----        ----        ----
Object1           property    property    property
Object2           property    property    property
Object3           property    property    property
解决方案

You need to add the parent keyname as a property Name to the nested objects:

$json.Object | ForEach-Object {
  foreach ($p in $_.PSObject.Properties) {
    $p.Value | Select-Object @{n='Name';e={$p.Name}},*
  }
}

Note that PowerShell will render the output in list form by default, since your objects have more than 4 properties. Pipe it through Format-List -AutoSize to get tabular output.

这篇关于格式化由Invoke-RestMethod或ConvertFrom-Json返回的[pscustomobject]实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 19:37