Powershell将json嵌套到重复的csv

时间:2019-05-31 20:30:03

标签: json powershell csv

种类类似于Convert nested JSON array into separate columns in CSV file,但不是平化的csv(即学科_01,discicpline_01)导出到csv的多行:

{
"data": [{
    "attributes": {
        "id": 10011,
        "title": "Test procedure",
        "slug": "slug",
        "url": "http://test.test",
        "disciplines": [
            "discipline_a",
            "discipline_b",
            "discipline_c"
        ]
    }
}]
}

导出到

"id","title","slug","url","discipline"
"10011","Test procedure","slug","http://test.test","discipline_a"
"10011","Test procedure","slug","http://test.test","discipline_b"
"10011","Test procedure","slug","http://test.test","discipline_c"

感谢Export fields with nested values from JSON to CSV到此为止:

$foo = invoke-restmethod $restquery -headers $headers
$foo | 
select -ExpandProperty data | 
select -ExpandProperty attributes |
select id, title, slug, url, disciplines | 
   foreach { 
        $_.disciplines = $_disciplines -join ' ' 
        $_ | 
export-csv c:\outfile.csv -notypeinformation

这给了我

"10011","Test procedure","slug","http://test.test","discipline_a discipline_b discipline_c"

但是不知道如何到达:

"id","title","slug","url","discipline"
"10011","Test procedure","slug","http://test.test","discipline_a"
"10011","Test procedure","slug","http://test.test","discipline_b"
"10011","Test procedure","slug","http://test.test","discipline_c"

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

虽然您发布的Json无效,
这可能会做到:

## Q:\Test\2019\05\31\SO_56401395.ps1
$foo = invoke-restmethod $restquery -headers $headers

$Data = $foo.data.attributes | ForEach-Object {
    foreach ($discipline in $_.disciplines}(
        [PSCustomObject]@{
            id         = $_.id
            title      = $_.title
            slug       = $_.slug
            url        = $_.url
            discipline = $discipline
        }
    }
}
$Data | Export-Csv c:\outfile.csv -NoTypeInformation