2

我正在使用 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}
]
4

1 回答 1

3

发生这种情况的原因是Import-Csv为每列创建一个具有字符串属性的对象,因此ConvertTo-Json为您提供带引号的字符串。您可以在Import-CsvConvertTo-Json之间使用Select-Object将数字属性重铸为整数,但我认为最简单的方法是在您的foreach块中添加正则表达式替换:

import-csv $_ | ConvertTo-Json -Compress | 
    Foreach {$_ -creplace '"NULL"','null' -replace ':"([0-9]+)"',':$1'} | 
        Out-File ".\$basename.json"
于 2013-07-15T02:59:08.180 回答