我下面有一个JSON文件。我正在尝试展平并将其转换为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?"
}
]
}
我尝试了下面的代码,但出现错误“ header_item”。我希望将其压缩为csv文件。
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
答案 0 :(得分:0)
首先提供的json格式不正确(缺少括号),所以我认为它是:
{
"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?"
}
]
}
使用Export-Csv
时的第二件事PowerShell使用第一个对象来确定CSV标头,因此您将必须列出所有对象的所有属性
$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
此致