JadonR
JadonR

Reputation: 193

PowerShell failing to convert JSON to CSV

I have spent a bit of time researching how to convert Json to a CSV file using powershell but am failing to have it complete properly. Below is the syntax I have created:

$pathToOutputFile = "C:\OrderLinQ\TESTING\IN\CatalogsRetrieved\test.txt"
$pathToJsonFile = "C:\OrderLinQ\TESTING\IN\CatalogsRetrieved\test.json"
Get-Content -Path $pathToJsonFile |
    ConvertFrom-Json |
    ConvertTo-Csv -NoTypeInformation |
    Set-Content $pathToOutputFile

However, when I attempt to execute this, I get an argument exception error:

ConvertFrom-Json : Invalid array passed in, ']' expected. (1): [
At line:1 char:69
+ Get-Content "C:\OrderLinQ\TESTING\IN\CatalogsRetrieved\test.json" | ConvertFrom- ...
+                                                                     ~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

enter image description here

Any thoughts as to what I'm doing wrong? I've verified my file using JSONLint and it shows verified. Example file can be found at https://api.myjson.com/bins/mo59w. Any help is appreciated!

Upvotes: 0

Views: 539

Answers (1)

HariHaran
HariHaran

Reputation: 4179

Try this. I've also attached the output

$pathToOutputFile = "D:\output.csv"
$pathToJsonFile = "D:\test.json"
$json = Get-Content -Path $pathToJsonFile

    function ConvertFrom-JsonToCsv {
    param(
        [Parameter(ValueFromPipeline)]
        $json        
    )

    Process {
        ($json | ConvertFrom-Json) | ConvertTo-Csv -NoTypeInformation
    }
}

ConvertFrom-JsonToCsv $json | Set-Content $pathToOutputFile

Outputenter image description here

Upvotes: 0

Related Questions