2

I am using PowerShell to convert a CSV file to a JSON format. The problem is the CSV wraps double quotes around the column values, even integers. How do I convert them to integers during the conversion process?

This is the script I am using to convert a directory of *.csv files to *.json:

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

This is my source CSV:

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

And here is what it outputs:

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

How do I make it output this instead?:

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

1 Answer 1

3

The reason that's happening is that Import-Csv creates an object with a string property for each column, so ConvertTo-Json is giving you quoted strings. You could use Select-Object between Import-Csv and ConvertTo-Json to recast the number properties as integers, but I think the simplest way to do it is to add a regex replace in your foreach block:

import-csv $_ | ConvertTo-Json -Compress | 
    Foreach {$_ -creplace '"NULL"','null' -replace ':"([0-9]+)"',':$1'} | 
        Out-File ".\$basename.json"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.