#json #powershell #csv
#json #powershell #csv
Вопрос:
Вот как выглядит мой файл json :
{
"count": 12,
"name": "Daily Ticket",
"columnNames": [
"User",
"Channel",
"Date",
"# of Closed Incidents",
"Open",
"Response",
"Remark",
"Closed"
],
"rows": [
[
"abc",
"Service Web",
"u00272020-06-13 00:00:00u0027",
"1",
"0",
"0",
"this is a text,please replace with null",
"1"
],
[
"xyz",
"Email",
"u00272020-06-13 00:00:00u0027",
"21",
"1",
"0",
"this is a text,please replace with null",
"7"
]
]
}
Я хочу заменить все значения в столбцах примечания на null и преобразовать в файл csv с помощью powershell. Пожалуйста, помогите достичь этого.
Я хочу, чтобы имена столбцов отображались как заголовок, а строки — как строки, разделенные запятой в csv. Мой выходной csv-файл должен выглядеть следующим образом:
User,Channel,Date,# of Closed Incidents,Open,Response,Remark,Closed
abc,Service Web,u00272020-06-13 00:00:00u0027,1,0,0,,1
xyz,Email,u00272020-06-13 00:00:00u0027,1,0,0,,1
Ответ №1:
Преобразовать этот json в файл CSV не так сложно.
Просто загрузите JSON, преобразуйте его в объект и выполните цикл по свойствам, создавая массив новых объектов, которые вы можете сохранить как CSV:
$json = Get-Content -Path 'D:TestDailyTicket.json' -Raw | ConvertFrom-Json
$headers = $json.columnNames
$result = foreach ($row in $json.rows) {
# just a precaution to not run into index errors when there are
# more items in the array than there are headers or vice-versa
$items = [math]::Min($row.Count, $headers.Count)
# create a new empty (ordered) hashtable
$hash = [ordered]@{}
for ($i = 0; $i -lt $items; $i ) {
# fill the hashtable, except for iten 'Remark'
$hash[$headers[$i]] = if ($headers[$i] -ne 'Remark') { $row[$i] } else { $null }
}
# If you insist on keeping the apostrophe characters in the date field in unicode format `u0027`
# $hash['Date'] = $hash['Date'] -replace "'", 'u0027'
# output a PSObject to be collected in array $result
[PsCustomObject]$hash
}
# output on screen
$result | Format-Table -AutoSize
# output to CSV file
$result | Export-Csv -Path 'D:TestDailyTicket.csv' -NoTypeInformation
Результирующий файл CSV:
"User","Channel","Date","# of Closed Incidents","Open","Response","Remark","Closed"
"abc","Service Web","'2020-06-13 00:00:00'","1","0","0",,"1"
"xyz","Email","'2020-06-13 00:00:00'","21","1","0",,"7"