json - 格式化 Invoke-RestMethod 或 ConvertFrom-Json 返回的 [pscustomobject] 实例

标签 json powershell formatting output-formatting

我正在尝试从我从 RESTful API 接收到的 JSON 文件创建一个表。

当我打印 json 对象的属性时,我得到如下输出:

PS> 写入输出 JSON.Object

对象 1 : @{key1=property; key2=属性; key3=属性; key4=属性}
对象 2 : @{key1=property; key2=属性; key3=属性; key4=属性}
对象 3 : @{key1=property; key2=属性; key3=属性; key4=属性}
对象 4 : @{key1=property; key2=属性; key3=属性; key4=属性}

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

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

此外,是否可以避免显示特定键及其属性?

例子:

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

最佳答案

您需要将父键名添加为属性 Name到嵌套对象:

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

请注意,PowerShell 将默认以列表形式呈现输出,因为您的对象具有 4 个以上的属性。管道通过 Format-List -AutoSize得到表格输出。

关于json - 格式化 Invoke-RestMethod 或 ConvertFrom-Json 返回的 [pscustomobject] 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41089151/

相关文章:

python - 在 Python 中指定数字(不带小数点)

python - 在一行上打印 `numpy.ndarray`

emacs - 有什么方法可以让 org-babel 正确缩进 noweb 纠结的代码吗?

c# - 使用不同的名称反序列化属性?

powershell - 将 csv 文件中的记录转换为字符串(如果作为 .txt 文件打开会显示什么)

java - 从 Socket.IO 获取和保存 JSON 数组

winforms - Windows窗体-摆脱等待光标

powershell - 在 Powershell 中启用 IIS 应用程序的身份验证

java - 如何通过Spring Integration连接SOAP服务器和JSON客户端?

java - org.json.JSONException : No value for id - IMPOSSIBLE TO SOLVE