Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert CSV to JSON and JSON to CSV using PowerShell

I have a CSV file that I am trying to convert to JSON using PowerShell.

The CSV file contains the following data.

web_url.csv

wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/

I would like to convert to json in the following format. Similarly how do you convert this json back to original csv in the format shown above?

web_url.json

{
    "wikipedia": "https://en.wikipedia.org/wiki/%s",
    "wolframalpha": "http://www.wolframalpha.com/input/?i=%s",
    "drive": "http://www.drive.google.com/"
}

When I run the command,

Get-Content -path web_url.csv | ConvertFrom-Csv -Delimiter ',' | ConvertTo-Json

it returns the following output which is not what I want.

[
    {
        "wikipedia":  "wolframalpha",
        "https://en.wikipedia.org/wiki/%s":  "http://www.wolframalpha.com/input/?i=%s"
    },
    {
        "wikipedia":  "drive",
        "https://en.wikipedia.org/wiki/%s":  "http://www.drive.google.com/"
    }
]
like image 426
Ishan Avatar asked Sep 15 '26 03:09

Ishan


2 Answers

# PowerShell script

import-csv "SampleInput.csv" | ConvertTo-Json | Add-Content -Path "output.json"
like image 128
GOLDY MANIKOTH Avatar answered Sep 18 '26 13:09

GOLDY MANIKOTH


Your csv doen't look like a "proper" csv to me: columns are swapped with rows. If you have control over input file, you may fix it there already:

@'
wikipedia,wolframalpha,drive
https://en.wikipedia.org/wiki/%s,http://www.wolframalpha.com/input/?i=%s,http://www.drive.google.com/
'@ | ConvertFrom-Csv | ConvertTo-Json

If that is not possible, you just have to perform some extra steps to get what you need:

$propertyList = @'
wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/
'@ | ConvertFrom-Csv -Header Name, Value

$properties = [ordered]@{}

foreach ($property in $propertyList) {
    $properties.Add($property.Name, $property.Value)
}

New-Object PSObject -Property $properties | ConvertTo-Json

And back, again - some extra work is required:

(@'
{
    "wikipedia":  "https://en.wikipedia.org/wiki/%s",
    "wolframalpha":  "http://www.wolframalpha.com/input/?i=%s",
    "drive":  "http://www.drive.google.com/"
}
'@ | ConvertFrom-Json).PSObject.Properties |
    Select-Object Name, Value |
    ConvertTo-Csv -NoTypeInformation |
    Select-Object -Skip 1
like image 22
BartekB Avatar answered Sep 18 '26 13:09

BartekB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!