以下 JSON 包含单独的属性,分别描述标题(列名称)(
columns
) 和相应行值的数组 (rows
):
{
"columns": [
{
"name": "ColumnName1",
"type": "Number"
},
{
"name": "ColumnName2",
"type": "String"
},
{
"name": "ColumnName3",
"type": "String"
}
],
"rows": [
[
11111,
"ResourceType1",
"String1"
],
[
22222,
"ResourceType2",
"String2"
],
[
33333,
"ResourceType3",
"String3"
]
]
}
如何将此 JSON 输入转换为其表示的 CSV 数据?
请注意,CSV 文件没有数据类型的概念 - 所有值都是字符串, 因此数据类型信息(来自
.column.type
属性)会丢失,除非您选择合并它
以某种方式作为 CSV 的使用者必须了解的约定(下面的代码不这样做)。
假设问题中的JSON保存在文件
file.json
中,通过使用[pscustomobject]
将文件读取为文本,可以使用
ConvertFrom-Json
将其解析为(
Get-Content
)对象图:
# Convert the JSON text into a [pscustomobject] object graph.
$fromJson = ConvertFrom-Json (Get-Content -Raw file.json)
# Process the array of column names and the arrays of row values by
# enclosing the array elements in "..." and joining them with ","
(, $fromJson.Columns.Name + $fromJson.Rows).ForEach({
$_.ForEach({ '"{0}"' -f ($_ -replace '"', '""') }) -join ','
})
请注意,上面将列名称和值括在
"..."
中,以便也支持
带有 embedded ,
字符的名称和值;此外,任何嵌入的 "
字符都可以通过 加倍 来正确转义。
如果您知道输入数据既不包含嵌入的值
,
也不包含
"
,可以简单省略内部.ForEach()
数组方法
上面调用,这将导致 unquoted 值。
以上输出:
"ColumnName1","ColumnName2","ColumnName3"
"11111","ResourceType1","String1"
"22222","ResourceType2","String2"
"33333","ResourceType3","String3"
要将上面的内存转换为代表CSV数据的(
[pscustomobject]
)对象,请使用ConvertFrom-Csv
(...
代表上面的命令):
... | ConvertFrom-Csv
Set-Content
:
... | Set-Content -Encoding utf8 out.csv