我使用PowerShell将CSV文件转换为JSON格式。问题是CSV在列值周围包含双引号,甚至是整数。如何在转换过程中将它们转换为整数?
这是我用来将* .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}
]
答案 0 :(得分:3)
发生这种情况的原因是 Import-Csv 会为每列创建一个带字符串属性的对象,因此 ConvertTo-Json 会为您提供带引号的字符串。您可以在 Import-Csv 和 ConvertTo-Json 之间使用选择对象将数字属性重铸为整数,但我认为最简单的方法是这是在 foreach 块中添加正则表达式替换:
import-csv $_ | ConvertTo-Json -Compress |
Foreach {$_ -creplace '"NULL"','null' -replace ':"([0-9]+)"',':$1'} |
Out-File ".\$basename.json"