如何用PowerShell从JSON文件构建数组并转换为CSV或表格格式
问题
我有一个JSON格式的数据源文件,希望将其导出或转换为CSV格式或指定结构的表格。JSON文件内容如下:
[ { "host_display_name" : "DCWKS10", "host_groups" : [ "Windows", "WINDOWS" ], "next_check" : 1698741835, "notes" : "", "notes_expanded" : "", "notes_url" : "", "notes_url_expanded" : "", "notification_interval" : 0.0, "notification_period" : "TP", "notifications_enabled" : 1, "obsess_over_service" : 1, "peer_key" : "7215e", "peer_name" : "Nagios", "percent_state_change" : 0.0, "perf_data" : "'E:\\ Used Space'=1475.08Gb;1474.56;1556.48;0.00;1638.40", "plugin_output" : "E:\\ - total: 1638.40 Gb - used: 1475.08 Gb (90%) - free 163.32 Gb (10%)", "process_performance_data" : 1, "retry_interval" : 1.0, "scheduled_downtime_depth" : 0, "state" : 1, "state_order" : 1, "state_type" : 1 }, { "host_display_name" : "DCWKS50", "host_groups" : [ "Windows", "WINDOWS" ], "next_check" : 1698741896, "notes" : "", "notes_expanded" : "", "notes_url" : "", "notes_url_expanded" : "", "notification_interval" : 0.0, "notification_period" : "TP", "notifications_enabled" : 1, "obsess_over_service" : 1, "peer_key" : "7215e", "peer_name" : "Nagios", "percent_state_change" : 0.0, "perf_data" : "C=86.15;106.73;106.73;0;106.73 ", "plugin_output" : "CRITICAL - Disk D: 24.75 Gb (1.7%) Free", "process_performance_data" : 1, "retry_interval" : 1.0, "scheduled_downtime_depth" : 0, "state" : 2, "state_order" : 4, "state_type" : 1 } ]
我已能获取$jsonObj.host_display_name、$jsonObj.host_groups等变量,但不知道如何构建出如下指定结构的数组/表格:
| host_display_name | host_groups |
|---|---|
| DCWKS10 | WINDOWS |
| DCWKS50 | WINDOWS |
解决方案
1. 使用Python处理
直接读取JSON文件,提取目标字段(host_groups取数组第二个元素),生成CSV或表格:
import json import csv # 读取JSON文件 with open('data.json', 'r') as f: data = json.load(f) # 提取需要的字段 processed_data = [] for item in data: processed_data.append({ 'host_display_name': item['host_display_name'], 'host_groups': item['host_groups'][1] }) # 导出为CSV with open('output.csv', 'w', newline='') as csvfile: fieldnames = ['host_display_name', 'host_groups'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for row in processed_data: writer.writerow(row) # 打印表格格式 print("| host_display_name | host_groups |") print("|-------------------|-------------|") for row in processed_data: print(f"| {row['host_display_name']:<19} | {row['host_groups']:<11} |")
2. 使用PowerShell处理
基于已有的$jsonObj变量,处理后导出CSV或输出表格:
# 提取目标字段,host_groups取数组第二个元素 $processedData = $jsonObj | ForEach-Object { [PSCustomObject]@{ host_display_name = $_.host_display_name host_groups = $_.host_groups[1] } } # 导出为CSV $processedData | Export-Csv -Path "output.csv" -NoTypeInformation # 输出表格格式 $processedData | Format-Table -AutoSize
3. 通用核心逻辑
不管用哪种语言,核心步骤一致:
- 遍历JSON数组中的每个对象
- 提取
host_display_name字段值 - 提取
host_groups数组中的指定元素(这里是索引1的元素) - 将两个值组合为一行数据,存入新数组
- 用新数组生成CSV文件或渲染表格
内容的提问来源于stack exchange,提问作者staxxoverflow
相关产品推荐
相关产品推荐

