Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON to CSV using PowerShell

I have a sample JSON-formatted here which converts fine if I use something like: https://konklone.io/json/

I've tried the following code in PowerShell:

(Get-Content -Path $pathToJsonFile | ConvertFrom-Json) 
| ConvertTo-Csv -NoTypeInformation 
| Set-Content $pathToOutputFile

But the only result I get is this:

{"totalCount":19,"resultCount":19,"hasMore":false,"results":

How do I go about converting this correctly in PowerShell?

like image 553
Anders Ekelund Avatar asked Apr 24 '17 18:04

Anders Ekelund


People also ask

How do I convert JSON data to CSV in PowerShell?

To convert the JSON file to the CSV file using PowerShell, we need to use the ConvertTo-CSV command as a pipeline. For example, we have a JSON file called PatchingServer. JSON stored at C:\temp and its content is as below.

How do I convert PowerShell to CSV?

You can use the Export-Csv cmdlet to convert objects to CSV strings. Export-CSV is similar to ConvertTo-CSV , except that it saves the CSV strings to a file. The ConvertTo-CSV cmdlet has parameters to specify a delimiter other than a comma or use the current culture as the delimiter.


2 Answers

By looking at just (Get-Content -Path $pathToJsonFile) | ConvertFrom-Json it looks like the rest of the JSON is going in to a results property so we can get the result I think you want by doing:

((Get-Content -Path $pathToJsonFile) | ConvertFrom-Json).results |
    ConvertTo-Csv -NoTypeInformation |
    Set-Content $pathToOutputFile

FYI you can do ConvertTo-Csv and Set-Content in one move with Export-CSV:

((Get-Content -Path $pathToJsonFile) | ConvertFrom-Json).results |
    Export-CSV $pathToOutputFile -NoTypeInformation
like image 87
Mark Wragg Avatar answered Oct 04 '22 04:10

Mark Wragg


You have to select the results property inside your CSV using the Select-Object cmdlet together with the -expand parameter:

Get-Content -Path $pathToJsonFile  | 
    ConvertFrom-Json | 
    Select-Object -expand results | 
    ConvertTo-Csv -NoTypeInformation |
    Set-Content $pathToOutputFile
like image 43
Martin Brandl Avatar answered Oct 04 '22 03:10

Martin Brandl