Page 1 of 1

On the sidelines of instrument creation : Powershell corner - CSV to JSON conversion

Posted: Thu Jun 23, 2022 1:03 pm
by SimPassion
 
Quick method, fast execution, free, with no pain and before someone is asking : yes it works on any platform, Linux, MacOS, Windows, by using PowerShell Core install named PSHost on all platforms

in two line :

Code: Select all

$csv = import-csv .\my_csv_data.csv
$csv | convertto-json | out-file .\my_json_data.json

# or more universal, with "\" replaced by "/" notation

$csv = import-csv ./my_csv_data.csv
$csv | convertto-json | out-file ./my_json_data.json
image.png
image.png (4.78 KiB) Viewed 450 times

in one line only :

Code: Select all

$csv = import-csv .\my_csv_data.csv | convertto-json | out-file .\my_json_data.json

# or more universal, with "\" replaced by "/" notation

$csv = import-csv ./my_csv_data.csv | convertto-json | out-file ./my_json_data.json
image.png
image.png (3.58 KiB) Viewed 449 times

in more detailed way :

Code: Select all

$csv = import-csv .\my_csv_data.csv		# at first, we import the CSV file from the current folder (".\" before the filename), into the $csv object variable, from the ".csv" file
$json = $csv | convertto-json			# the $csv object is converted to JSON format with maintaining its current data content and the result is put into the $json object variable
$json						# this line will only display the result in the PowerShell console
$json | out-file .\my_json_data.json		# the $json content is written as output file, into the designated ".json" filename, in the current folder (".\" before the filename)

# or more universal, with "\" replaced by "/" notation

$csv = import-csv ./my_csv_data.csv		# at first, we import the CSV file from the current folder ("./" before the filename), into the $csv object variable, from the ".csv" file
$json = $csv | convertto-json			# the $csv object is converted to JSON format with maintaining its current data content and the result is put into the $json object variable
$json						# this line will only display the result in the PowerShell console
$json | out-file ./my_json_data.json		# the $json content is written as output file, into the designated ".json" filename, in the current folder ("./" before the filename)

Re: On the sidelines of instrument creation : Powershell corner - CSV to JSON conversion

Posted: Thu Jun 23, 2022 1:17 pm
by Keith Baxter
Interesting Gilles,

Will try it .

Keith