尝试在PowerShell中将嵌套的JSON文件转换为CSV

polkgigr  于 2023-09-27  发布在  Shell
关注(0)|答案(1)|浏览(94)

我试图使用PowerShell将嵌套的JSON文件转换为CSV文件,但无法找到正确的逻辑。这是我的示例JSON文件内容:

[
    {
        "Device":  "Device1",
        "Test":  [
                     {
                         "IP":  "10.20.3.6",
                         "Result":  "Fail"
                     }
                 ]
    },
    {
        "Device":  "Device2",
        "Test":  [
                     {
                         "IP":  "10.124.102.100",
                         "Result":  "Fail"
                     },
                     {
                         "IP":  "107.12.13.51",
                         "Result":  "Fail"
                     }
                 ]
    }
]

我正在尝试的代码

$JsonData = Get-Content '.\Report_202104262250.json' -Raw | ConvertFrom-Json  $JsonData | Select-Object -Property Device, @{Name = 'IP'; Expression = { foreach ($ip in $_.Test.IP) {$ip} }}, @{Name = 'Result'; Expression = {$_.Test.Result}}

这是我正在寻找的csv输出

Device  Test__IP        Test__Result
Device1 10.20.3.6       Fail
Device2 10.124.102.100  Fail
Device2 107.12.13.51    Fail

已尝试其他帮助资源,但无法实现。请需要帮助。

pn9klfpd

pn9klfpd1#

# Load the json and convert to objects
$json = Get-Content .\json.json | ConvertFrom-Json

# Create custom objects
$json | ForEach-Object {
    $Device = $_.Device
    # Iterate through each of the tests and create object for each
    $_.Test | ForEach-Object {
        [PSCustomObject]@{
            'Device'       = $Device
            'Test__IP'     = $_.IP
            'Test__Result' = $_.Result
        }
    }
} | Export-Csv -Path .\Test_Output.csv -NoTypeInformation

相关问题