使用PowerShell合并含唯一ID的两个JSON文件并转为CSV
PowerShell合并JSON并转换为可用CSV的解决方案
一、合并两个JSON文件
先读取两个JSON文件,通过唯一ID(注意两个文件的ID大小写不同,需统一匹配)将tags属性合并到第二个JSON的对象中:
# 读取两个JSON文件 $json1 = Get-Content -Path "path/to/json1.json" | ConvertFrom-Json $json2 = Get-Content -Path "path/to/json2.json" | ConvertFrom-Json # 遍历json2的每个对象,匹配json1中对应ID的tags属性 $mergedJson = $json2 | ForEach-Object { $currentId = $_.ID # 查找json1中id匹配的项 $matchingTags = $json1 | Where-Object { $_.id -eq $currentId } | Select-Object -ExpandProperty tags # 将tags添加到当前对象 $_ | Add-Member -MemberType NoteProperty -Name "tags" -Value $matchingTags -Force $_ } # 输出合并后的JSON(可选,保存到文件) $mergedJson | ConvertTo-Json -Depth 10 | Out-File "path/to/merged.json"
二、将合并后的JSON转换为可用CSV
直接使用ConvertTo-CSV会把嵌套的tags对象显示为哈希表字符串(比如@{tag1=value1; tag2=value2}),无法直接使用。可以通过两种方式解决:
方式1:扁平化嵌套的tags属性
将每个tag作为CSV的单独列:
$flattenedData = $mergedJson | ForEach-Object { # 提取基础属性 $baseProps = $_ | Select-Object ID, Name, State # 展开tags的键值对为独立属性 $tagProps = $_.tags | Get-Member -MemberType NoteProperty | ForEach-Object { [PSCustomObject]@{ Name = $_.Name Value = $_.Value } } | Group-Object -AsHashTable -AsString # 合并基础属性与tag属性 $combined = $baseProps.PSObject.Copy() $tagProps.GetEnumerator() | ForEach-Object { $combined | Add-Member -MemberType NoteProperty -Name $_.Key -Value $_.Value -Force } $combined } # 转换为CSV并保存 $flattenedData | ConvertTo-Csv -NoTypeInformation | Out-File "path/to/flattened.csv"
方式2:将tags序列化为JSON字符串
如果需要保留tags的结构,可将其转为JSON字符串存储在CSV的单独列中:
$csvReadyData = $mergedJson | ForEach-Object { $_ | Select-Object ID, Name, State, @{Name="tags"; Expression={ $_.tags | ConvertTo-Json -Compress }} } # 转换为CSV并保存 $csvReadyData | ConvertTo-Csv -NoTypeInformation | Out-File "path/to/tags-as-json.csv"
内容的提问来源于stack exchange,提问作者Vauler
相关产品推荐
相关产品推荐

