问题
I have a JSON file below. I am trying to flatten and convert it to CSV.
{
"tempid": "template_86CE6E3BE3AD4EAB95727BCBFAD6A83C",
"auid": "audit_00006F5D7A114CE59AD572E3E878E726",
"created_at": "2017-01-12T08:54:48.835Z",
"Dateat": "2019-04-26T14:24:09.496Z",
"Datefrom": {
"score": 64,
"duration": 1754,
"space": {
"device_id": "88888888888888",
"owner": "John Paul"
},
"header_items": [
{
"item_id": "357085FF-B66A-4C28-B9D",
"children": "66f7893245d45-ea77-0020"
},
{
"parent_id": "357949D",
"item_id": "f3789245d40-ea7o89797a66",
"label": "Audit Title",
"options": "@{is_mandatory=False}",
"responses": "@{text=}"
}
],
"items": [
{
"parent_id": "81C1FFE",
"item_id": "B9CD2607897898-427898",
"label": "TURN LEFT.",
"type": "category"
},
{
"parent_id": "456487k78978578",
"item_id": "687fgfgfd",
"label": "ANY RUBBISH?"
}
]
}
I have tried the code below and I get errors "header_item" cannot be found. I would like it flatten into csv files.
Get-Content C:\can\Test\XY.json -Raw |
ConvertFrom-Json |
Select -Expand header_items |
Select -Expand items |
Export-Csv C:\can\Test\XY.csv -NoTypeInformation
回答1:
First thing provided json is malformed (missing brackets) so i assume its:
{
"tempid": "template_86CE6E3BE3AD4EAB95727BCBFAD6A83C",
"auid": "audit_00006F5D7A114CE59AD572E3E878E726",
"created_at": "2017-01-12T08:54:48.835Z",
"Dateat": "2019-04-26T14:24:09.496Z",
"Datefrom": {},
"score": 64,
"duration": 1754,
"space": {
"device_id": "88888888888888",
"owner": "John Paul"
},
"header_items": [
{
"item_id": "357085FF-B66A-4C28-B9D",
"children": "66f7893245d45-ea77-0020"
},
{
"parent_id": "357949D",
"item_id": "f3789245d40-ea7o89797a66",
"label": "Audit Title",
"options": "@{is_mandatory=False}",
"responses": "@{text=}"
}
],
"items": [
{
"parent_id": "81C1FFE",
"item_id": "B9CD2607897898-427898",
"label": "TURN LEFT.",
"type": "category"
},
{
"parent_id": "456487k78978578",
"item_id": "687fgfgfd",
"label": "ANY RUBBISH?"
}
]
}
Second thing when using Export-Csv
PowerShell uses the first object to determine the CSV headers, so you will have to list list all properties of all objects
$sourceFilePath = "C:\can\Test\XY.json"
$json = Get-Content $sourceFilePath -Raw | ConvertFrom-Json
$all = @( ($json.header_items | Select-Object *, @{Name = 'ItemType'; Expression = { 'HeaderItem' } }) ) + ($json.items | Select-Object *, @{Name = 'ItemType'; Expression = { 'Item' } })
$properties = ($all | ForEach-Object { $_ | Get-Member -MemberType NoteProperty}) | Select-Object -Unique -ExpandProperty Name
$destinationFilePath = "C:\can\Test\XY.jcsv"
$all | Select-Object -Property $properties | Export-Csv -NoTypeInformation -Path $destinationFilePath
Csv file opened and formatted with Excel
Regards,
来源:https://stackoverflow.com/questions/58031293/powershell-flattening-nested-json-and-convert-it-to-csv