2013-07-14 56 views
2

我正在使用PowerShell將CSV文件轉換爲JSON格式。問題在於CSV包圍了列值的雙引號,甚至整數。如何在轉換過程中將它們轉換爲整數?如何使用ConvertTo-Json將字符串轉換爲整數?

這是我使用轉換的*的.csv文件的目錄的腳本*以.json:

Get-ChildItem .\*.csv | Foreach-Object { 
    $basename = $_.BaseName 
    import-csv $_ | ConvertTo-Json -Compress | Foreach {$_ -creplace '"NULL"','null'} | Out-File ".\$basename.json" 
} 

這是我的源CSV:

"Id","Name","Active" 
"1","Test 1","1" 
"2","Test 2","0" 
"3","Test 3","1" 

,這裏是什麼輸出:

[ 
{"Id":"1","Name":"Test 1","Active":"1"} 
{"Id":"2","Name":"Test 2","Active":"0"} 
{"Id":"3","Name":"Test 3","Active":"1"} 
] 

如何使它輸出這個代替?:

[ 
{"Id":1,"Name":"Test 1","Active":1} 
{"Id":2,"Name":"Test 2","Active":0} 
{"Id":3,"Name":"Test 3","Active":1} 
] 

回答

3

這是發生的原因是,進口-CSV有一個字符串屬性爲每個列創建一個對象,所以的ConvertTo JSON的是給你帶引號的字符串。你可以使用選擇-對象進口-CSV之間的ConvertTo JSON的重鑄數量的屬性爲整數,但我認爲這樣做是爲了增加一個正則表達式在你的foreach塊替換最簡單的方法:

import-csv $_ | ConvertTo-Json -Compress | 
    Foreach {$_ -creplace '"NULL"','null' -replace ':"([0-9]+)"',':$1'} | 
     Out-File ".\$basename.json"