在Powershell中从JSON转换为CSV [英] Convert to csv from json in powershell
问题描述
这是我的csv:
"name,data
Play,http://{gho}.domain.com/
BDomain,domain.com
Charts,2
Compress,0
CompressJ,0" | ConvertFrom-Csv | ConvertTo-Json
给我:
[
{
"name": "Play",
"data": "http://{gho}.domain.com/"
},
{
"name": "BDomain",
"data": "domain.com"
},
{
"name": "Charts",
"data": "2"
},
{
"name": "Compress",
"data": "0"
},
{
"name": "CompressJ",
"data": "0"
}
]
我现在想从json中获取该csv,但是|的链ConvertFrom-Json |ConvertTo-CSV无法正常工作,我很好奇为什么不这样做?
I would now like to get that csv back from my json, however the chains of | ConvertFrom-Json | ConvertTo-CSV are not working, and I am curious why not?
推荐答案
以简洁的摘要补充 Steven的有用答案以及跨版本的观点:
To complement Steven's helpful answer with a succinct summary and a cross-edition perspective:
-
在 PowerShell [Core] v7 + 中,不需要额外的工作:附加
|ConvertFrom-Json |将ConvertTo-Csv
转换为您的代码即可.
In PowerShell [Core] v7+, no extra effort is needed: appending
| ConvertFrom-Json | ConvertTo-Csv
to your code works as-is.
在 Windows PowerShell和PowerShell [Core] v6.x 中,您需要强制枚举 ConvertFrom-Json
的枚举输出以使 ConvertTo-Csv
正常工作,因为与PowerShell的通常行为相反, ConvertFrom-Json
将JSON数组作为一个对象整体输出进入管道.
In Windows PowerShell and PowerShell [Core] v6.x, you need to force enumeration of ConvertFrom-Json
's output in order for ConvertTo-Csv
to work correctly, because, against PowerShell's usual behavior, ConvertFrom-Json
outputs a JSON array as a whole, as a single object to the pipeline.
-
此行为是不寻常的事实,促使v7 +发生了更改-请参见此答案以获取背景信息.
It is the fact that this behavior is unusual that prompted the v7+ change - see this answer for background information.
强制枚举的最简单方法-即将输出为一个整体的数组/集合的元素一对一发送到管道是使用(.)
,
The simplest way to force enumeration - i.e. to send an output-as-a-whole array's / collection's elements one by one to the pipeline is to use (...)
, the grouping operator.
# Works in all PowerShell versions, but in v7+ the (...) is no longer necessary.
(
"name,data
Play,http://{gho}.domain.com/
BDomain,domain.com
Charts,2
Compress,0
CompressJ,0" | ConvertFrom-Csv | ConvertTo-Json |
ConvertFrom-Json
) | ConvertTo-Csv -NoTypeInformation
这将产生:
"name","data"
"Play","http://{gho}.domain.com/"
"BDomain","domain.com"
"Charts","2"
"Compress","0"
"CompressJ","0"
这篇关于在Powershell中从JSON转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!