使用 PowerShell 将 JSON 转换为 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43594860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:51:08  来源:igfitidea点击:

Convert JSON to CSV using PowerShell

jsonpowershellcsv

提问by Anders Ekelund

I have a sample JSON-formatted herewhich converts fine if I use something like: https://konklone.io/json/

在这里有一个 JSON 格式的示例,如果我使用以下内容,它可以很好地转换:https: //konklone.io/json/

I've tried the following code in PowerShell:

我在 PowerShell 中尝试了以下代码:

(Get-Content -Path $pathToJsonFile | ConvertFrom-Json) 
| ConvertTo-Csv -NoTypeInformation 
| Set-Content $pathToOutputFile

But the only result I get is this:

但我得到的唯一结果是:

{"totalCount":19,"resultCount":19,"hasMore":false,"results":

How do I go about converting this correctly in PowerShell?

如何在 PowerShell 中正确转换它?

回答by Mark Wragg

By looking at just (Get-Content -Path $pathToJsonFile) | ConvertFrom-Jsonit looks like the rest of the JSON is going in to a resultsproperty so we can get the result I think you want by doing:

通过查看(Get-Content -Path $pathToJsonFile) | ConvertFrom-Json它的其余部分 JSON 似乎进入了一个results属性,因此我们可以通过执行以下操作来获得我认为您想要的结果:

((Get-Content -Path $pathToJsonFile) | ConvertFrom-Json).results |
    ConvertTo-Csv -NoTypeInformation |
    Set-Content $pathToOutputFile

FYI you can do ConvertTo-Csvand Set-Contentin one move with Export-CSV:

仅供参考,你可以做ConvertTo-Csv,并Set-Content与一招Export-CSV

((Get-Content -Path $pathToJsonFile) | ConvertFrom-Json).results |
    Export-CSV $pathToOutputFile -NoTypeInformation

回答by Martin Brandl

You have to select the resultsproperty inside your CSV using the Select-Objectcmdlet together with the -expandparameter:

您必须results使用Select-Objectcmdlet 和-expand参数选择CSV 中的属性:

Get-Content -Path $pathToJsonFile  | 
    ConvertFrom-Json | 
    Select-Object -expand results | 
    ConvertTo-Csv -NoTypeInformation |
    Set-Content $pathToOutputFile

回答by Pat Fahy

I was getting my json from a REST web api and found that the following worked:

我从 REST web api 获取我的 json 并发现以下内容有效:

Invoke-WebRequest -method GET -uri $RemoteHost -Headers $headers 
 | ConvertFrom-Json 
 | Select-Object -ExpandProperty  <Name of object in json>
 | ConvertTo-Csv -NoTypeInformation 
 | Set-Content $pathToOutputFile

I end up with a perfectly formatted csv file