Convert CSV file to JSON file using PowerShell ignore scientific notation

360 Views Asked by At

I have .csv files containing long numbers. I used the following PowerShell script to convert from .csv file to .json. But the long numbers are importing as scientific notation.

How to force import long number from csv to json without converting to scientific notation?

Here is my PowerShell script,

import-csv -path "F:\DATA_002.csv" -UseCulture | select "Name", "Mobile", "Other mobile no." | ConvertTo-Json | Add-Content -Path "F:\DATA_002.json"
1

There are 1 best solutions below

0
Daniel On

As mclayton astutely pointed out in a comment, you may not be able to get the original number back however if you just want to get rid of the scientific notation you can try either of the following:

Import-Csv "F:\DATA_002.csv" -UseCulture | 
    ForEach-Object { $_."Other mobile no." = $_."Other mobile no." -as [long]; $_ } | 
        ConvertTo-Json | Add-Content -Path "F:\DATA_002.json"
Import-Csv "F:\DATA_002.csv" -UseCulture | 
    Select-Object Name, Mobile, @{n = 'Other'; e = { $_."Other mobile no." -as [long] } } | 
        ConvertTo-Json | Add-Content -Path "F:\DATA_002.json"

Both use converting the scientific notation text to a long object type using the -as operator.

A word of caution when using the -as operator. If the conversion fails, it will do so silently and the output will be null. If you'd rather it fail with notification, try casting the value to long rather than using -as

[long]$_."Other mobile no."