hwustrack
hwustrack

Reputation: 67

How to create CSV output from JSON?

My JSON query returns weather data that I would like to parse using powershell. I want to delete all unnecessary items and export the final file to CSV or txt.

$json = Get-Content -Raw $path | ConvertFrom-Json #get JSON object from directory and convert to powershell object
$hourly = $json.hourly_forecast
$FCTTIME = $hourly.FCTTIME
$pretty = $FCTTIME | Select pretty

$temp = $hourly.temp
$eng = $temp | Select english

$parsed = $eng, $pretty

It seems to work okay but when I output $parsed in CSV it has the object properties rather than the values of $eng and $pretty. Is there any easier way to parse JSON files or another way I can combine the arrays in the last step?

Upvotes: 1

Views: 3152

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Expand the properties. Also, Export-Csv exports the properties of objects, not the values of an array. Something like this should work:

Get-Content -Raw $path |
  ConvertFrom-Json |
  select -Expand hourly_forecast |
  select @{n='Pretty';e={$_.FCTTIME | select -Expand pretty}},
         @{n='English';e={$_.temp | select -Expand english}} |
  Export-Csv 'C:\output.csv' -NoType

Upvotes: 4

Related Questions