Convert JSON to CSV using PowerShell

后端 未结 3 2045
借酒劲吻你
借酒劲吻你 2020-12-16 21:51

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:



        
相关标签:
3条回答
  • 2020-12-16 22:30

    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
    
    0 讨论(0)
  • 2020-12-16 22:32

    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
    
    0 讨论(0)
  • 2020-12-16 22:37

    I was getting my json from a REST web api and found that the following worked:

    Invoke-WebRequest -method GET -uri $RemoteHost -Headers $headers 
     | ConvertFrom-Json 
     | Select-Object -ExpandProperty  <Name of object in json>
     | ConvertTo-Csv -NoTypeInformation 
     | Set-Content $pathToOutputFile
    
    I end up with a perfectly formatted csv file
    
    0 讨论(0)
提交回复
热议问题