我正在尝试使用 Powershell 自动化一些数据管道,但我有点坚持将 JSON 列表转换为 CSV 文件中每行一个单元格。希望你们中的一些人可以帮助我。
我得到的 JSON 如下所示:
{"result": [
{
"uid": "1",
"EducationHistory": []
},
{
"uid": "2",
"EducationHistory": []
},
{
"uid": "3",
"EducationHistory": []
},
{
"uid": "4",
"EducationHistory": {
"10466632": {
"euid": 10466632,
"degree": "Highschool",
"educationLevel": null
},
"10466634": {
"euid": 10466634,
"degree": "Law",
"educationLevel": "batchelor"
},
"10466635": {
"euid": 10466635,
"degree": "Law",
"educationLevel": "master"
}
}
},
{
"uid": "5",
"EducationHistory": {
"10482462": {
"euid": 10482462,
"degree": "IT",
"educationLevel": "master"
}
}
}
]
}
我想要做的是将每个 uid 的 educationLevel
收集在一列中。所以像这样:
uid | educationLevel
----+------------------
1 |
2 |
3 |
4 | barchelor, master
5 | master
通常我希望 Expandproperty 降到较低的级别,但这对于这种情况不起作用,因为每个 EducationHistory 条目都位于该特定条目的 euid 后面。由于记录数量太多,像下面的示例那样扩展其中的每一个是行不通的。
所以我认为我需要一些循环,但我不知道如何。希望你能帮我。第一次在这里发帖,我是一个 Powershell 新手,所以我希望我的问题很清楚。如果您需要更多信息,请告诉我。
单个条目的代码,例如:
$json = Get-content -raw -path C:\TEMP\File.json
(ConvertFrom-Json -InputObject $json).result |
Select-Object uid,
#Expand one of the entries:
@{Name = "Edu.Level";E={$_.EducationHistory | Select-Object -
expandproperty 10466632 |Select-Object -expandpropert degree }} |
Format-Table
最佳答案
$content = Get-Content .\test.json
$result = ($content | ConvertFrom-Json).result
$totalResult = @()
foreach($res in $result) {
$tempArray = @()
if($res.EducationHistory -ne $null) {
$properties = $res.EducationHistory | Get-Member -MemberType NoteProperty
foreach($property in $properties) {
$eduLevel = $res.EducationHistory.$($property.Name).educationLevel
if(![String]::IsNullOrEmpty($eduLevel)) {
$tempArray += $eduLevel
}
}
}
$totalResult += [PSCustomObject]@{
uid = $res.uid
educationLevel = $tempArray -join ", "
}
}
$totalResult
这将为您提供的输入输出所需的结果。
最棘手的部分是 EducationHistory
属性的值。您必须使用Get-Member
cmdlet(请参阅Get-Help Get-Member
)来获取循环中当前对象的属性。然后使用属性名称访问educationLevel
。
关于json - Powershell JSON管道将多个值扩展为一列csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52972046/