[英]Extracting particular columns from a json converted csv file using powershell, or from the initial json file itself
[英]Extracting fields to CSV from a JSON file with Powershell
我有一個從 API 中提取的 json,就像這樣:
{
"LPEONASVVAP0": {
"LPEONASVVAP0": {
"id": "urn:vcloud:vm:f526d27d-e0f9-4d4f-ae81-4824e397c027",
"name": "LPEONASVVAP0",
"description": "_vm_desc_",
"dateCreated": "2021-04-06T14:56:09.640+0000"
}
},
"WDEONDSVDIS6": {
"WDEONDSVDIS6": {
"id": "urn:vcloud:vm:7ed43492-a7ce-4963-b5bb-5ec2ca89477c",
"name": "WDEONDSVDIS6",
"description": "",
"dateCreated": "2021-04-13T13:44:29.973+0000"
}
},
"WDEONASVSTR0": {
"WDEONASVSTR0": {
"id": "urn:vcloud:vm:7afa34fe-b239-4abe-90df-3f270b44db1f",
"name": "WDEONASVSTR0",
"description": "",
"dateCreated": "2021-03-10T16:17:50.947+0000"
}
},
}
我只需要提取字段id、name 和 description來用它們創建 csv。 我對此進行了測試,但 output 文件為空白:
$pathToJsonFile = x
$pathToOutputFile = x
$obj = Get-Content $pathToJsonFile -Raw | ConvertFrom-Json
print $obj
$obj | select id, name, description | Convertto-csv > $pathToOutputFile
您需要通過psobject
隱藏成員集“發現”父屬性名稱(例如'LPEONASVVAP0'
)。 由於外部和內部屬性命名相同,我們可以重用名稱來獲取內部屬性值:
$obj.psobject.Properties |ForEach-Object {
$_.Value.$($_.Name)
} |Select id,name,description |Export-Csv -NoTypeInformation -Path $pathToOutputFile
編輯:馬蒂亞斯 R。 傑森斯的答案比這寫得更好,我會這樣做,而不是我發布的方式。
好的,所以我復制了您發布的 json,將其導入。 由於每個信息數組都是這樣存儲的
"WDEONDSVDIS6": {
"WDEONDSVDIS6": {
我使用get-member
來迭代每個 arrays 和 select 的信息。 此外,您不需要使用Convertto-csv > $pathToOutputFile
,而是使用export-csv
命令。 下面是我的代碼,我會怎么做,可能有更好的方法,但這有效:)
$pathToOutputFile = x.csv
$obj = Get-Content example.json -Raw| ConvertFrom-Json
$obj2 = ($obj | Get-Member -MemberType noteproperty).Name
$result = foreach($item in $obj2){
$obj.$item.$item | select id,name,description
}
$result | Export-Csv -Path $pathToOutputFile -Encoding utf8 -NoTypeInformation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.