简体   繁体   中英

Trying to convert nested JSON file to CSV in Powershell

I am trying to convert this nested JSON to CSV file using PowerShell This is my example JSON file content:

[
    {
        "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"
                     }
                 ]
    }
]

This is the csv output I am looking for

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

Tried other help resources but could not achieve it. Please help needed.

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM