我对PowerShell还是很陌生,我正在尝试将此JSON文件转换为CSV。
使用这样的简单代码:
$sourceFilePath = "Records.json"
$destinationFilePath = "Records.csv"
((Get-Content -Path $sourceFilePath -Raw) | ConvertFrom-Json) | Export-CSV $destinationFilePath -NoTypeInformation
因为我要使用System.Object [],所以我需要对contact_id,site_id,名字别名和别名进行某种扩展或“ ForEach”。我已经进行了一些搜索,但似乎无法将我的例子包裹住。另外,“名字别名”中的空格会增加复杂性。
我对源JSON没有任何控制。这是一个示例:
[
{
"mdm id" : "947b2a12-3aac-480a-a0bf-626aff106f48",
"first name" : "Claude",
"last name" : "Bones",
"contact_ids" : [
"CTP70499"
],
"site_ids" : [
"5015"
],
"first name aliases" : [
"Claude"
],
"aliases" : [
"Claude Bones"
],
"createdDate" : "2020-06-03T19:59:08Z",
"updatedDate" : "2020-06-03T20:48:27Z",
"veevaID" : "V0B000000000569"
},
{
"mdm id" : "bce21b05-0b28-4ebb-a34d-761c1a397821",
"first name" : "Daniel",
"last name" : "Smith",
"contact_ids" : [
"CTP699"
],
"site_ids" : [
"5015"
],
"first name aliases" : [
"Dan",
"Danial",
"Danne",
"Danny",
"Daniel"
],
"aliases" : [
"Daniel Smith"
],
"createdDate" : "2020-06-03T19:59:08Z",
"updatedDate" : "2020-06-03T20:48:27Z",
"veevaID" : "V0B000000000566"
}
]
答案 0 :(得分:2)
作为数组的值将需要合并为一个值。无论它具有多少值,如果在json中将其指定为数组[]
,都需要对其进行操作。互联网上有几篇文章和自定义函数。您的示例可以通过以下代码来处理。
$JSONdata = @'
[
{
"mdm id" : "947b2a12-3aac-480a-a0bf-626aff106f48",
"first name" : "Claude",
"last name" : "Bones",
"contact_ids" : [
"CTP70499"
],
"site_ids" : [
"5015"
],
"first name aliases" : [
"Claude"
],
"aliases" : [
"Claude Bones"
],
"createdDate" : "2020-06-03T19:59:08Z",
"updatedDate" : "2020-06-03T20:48:27Z",
"veevaID" : "V0B000000000569"
},
{
"mdm id" : "bce21b05-0b28-4ebb-a34d-761c1a397821",
"first name" : "Daniel",
"last name" : "Smith",
"contact_ids" : [
"CTP699"
],
"site_ids" : [
"5015"
],
"first name aliases" : [
"Dan",
"Danial",
"Danne",
"Danny",
"Daniel"
],
"aliases" : [
"Daniel Smith"
],
"createdDate" : "2020-06-03T19:59:08Z",
"updatedDate" : "2020-06-03T20:48:27Z",
"veevaID" : "V0B000000000566"
}
]
'@ | ConvertFrom-Json
$JSONdata | foreach {
$record = [ordered]@{}
foreach($property in $_.psobject.Properties)
{
if($property.value -is [string])
{
$record.Add($property.name,$property.value)
}
else
{
$record.Add($property.name,($property.value -join ', '))
}
}
[PSCustomObject]$record
} | ConvertTo-Csv -NoTypeInformation
输出
"mdm id","first name","last name","contact_ids","site_ids","first name aliases","aliases","createdDate","updatedDate","veevaID"
"947b2a12-3aac-480a-a0bf-626aff106f48","Claude","Bones","CTP70499","5015","Claude","Claude Bones","2020-06-03T19:59:08Z","2020-06-03T20:48:27Z","V0B000000000569"
"bce21b05-0b28-4ebb-a34d-761c1a397821","Daniel","Smith","CTP699","5015","Dan, Danial, Danne, Danny, Daniel","Daniel Smith","2020-06-03T19:59:08Z","2020-06-03T20:48:27Z","V0B000000000566"
只需将其更改为Export-Csv