question

BarryCuda-7859 avatar image
1 Vote"
BarryCuda-7859 asked WindosNZ answered

Powershell convert json

Have a powershell script to pull alerts from graph api and converts it to a JSON file. The JSON file has to be flat (ConvertTo-Json -Compress) for use in a different system. The script works great when it only returns a single alert if multiple alerts are returned instead of a json file with 2 lines I have one really long line.
How can I get the output to a single file with a line for each json

$response = Invoke-WebRequest -Method Get -Uri $url -Headers $headers -ErrorAction Stop
$alerts = ($response | ConvertFrom-Json).value | ConvertTo-Json -Compress -Depth 100
$alerts = $alerts -replace "\\n\\n", " "
$outputJsonPath = "$path\test.json
Out-File -FilePath $outputJsonPath -Encoding ascii -InputObject $alerts

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

WindosNZ avatar image
0 Votes"
WindosNZ answered

You're going to want to iterate over each alert and convert them each to JSON individually, otherwise you're converting an array of alerts into one json string (which when compressed will be on one continuous line).

Note that if you do convert each alert individually, the resulting file won't contain valid json (each line will be valid, but the collection of lines will be invalid)

Based on the snippet above, this should end up with one line of valid json per alert

 $Alerts = Invoke-RestMethod -Method Get -Uri $Url -Headers $Headers -ErrorAction Stop
    
 $OutputJsonPath = "$Path\test.json"
    
 foreach ($Alert in $Alerts.value) {
     $Alert | ConvertTo-Json -Compress -Depth 100 | Out-File -FilePath $outputJsonPath -Encoding ascii -Append
 }

(I don't know what format the result comes back in, $Alert in $Alerts.value may be able to just be $Alert in $Alerts)

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.