【问题标题】:Powershell convert columns of txt file to JSON formatPowershell将txt文件的列转换为JSON格式
【发布时间】:2021-12-11 22:06:13
【问题描述】:

我有以下输出(在文件 .txt 中)

Average:     CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
Average:     all    0.21    0.00    0.08    0.00    0.00    0.00    0.00    0.00    0.00   99.71
Average:       0    1.01    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   98.99
Average:       1    0.00    0.00    0.52    0.00    0.00    0.00    0.00    0.00    0.00   99.48

我需要在 Json 中解析 CPU 的数量(第一列)和最后一个(%idle)。

例如

[
  {
    "Num": "all",
    "Data": "99.71"
  },
  {
    "Num": "0",
    "Data": "98.99"
  },
  {
    "Num": "1",
    "Data": "99.48"
  }
]

但我得到以下输出:

[
  "Num_all 99.71",
  "Num_0 98.99",
  "Num_1 99.48"
]

Json 是有效的,但不幸的是这不是预期的输出。

我的代码:

$file = Join-Path $PSScriptRoot cpu.txt

#Create .temp file with the stats  
$cpu_stats = mpstat -P ALL 1 2 | grep Average > $file

#Print the first column (cpu num) and 11th (Average CPU)
$info_json = Get-Content $file | Select-object -skip 1| Foreach {"Num_$(($_ -split '\s+',12)[1,11])"} | ConvertTo-Json

#Print result (Json)
Write-Output $info_json

我如何使用 PowerShell 来获得它? 提前致谢

【问题讨论】:

    标签: json powershell parsing


    【解决方案1】:

    你需要用.Num.Data构造对象[pscustomobject]实例)properties来得到你想要的JSON格式:

    Get-Content $file | 
      ForEach-Object {
        # Extract the column values of interest...
        $cpu, $idle = (-split $_)[1, -1]
        # ... and use them to construct and output a custom object.
        [pscustomobject] @{
          Num = $cpu
          Data = $idle
        }
      } | ConvertTo-Json
    
    • 我使用了-split operator一元 形式将每一行用非空的空格分隔(同时忽略前导和尾随空格)。

    • 由于%idle列是最后一个,所以可以用索引-1引用。

    • $cpu, $idle = ... 是一个多重赋值,它将单独返回的两个数组元素赋值给指定的变量。

    • [pscustomobject] @{ ... } 是通过hashtable (@{ ... }) 构造[pscustomobject] 实例的语法糖。[1]


    [1] 请注意,使用此语法时实际上没有构建单独的哈希表。此外,与真正的哈希表不同,在这种情况下,指定的属性(键)的顺序是保留的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 2017-06-18
      • 1970-01-01
      • 2014-01-20
      相关资源
      最近更新 更多