Powershell convert json

Barry Cuda 26 Reputation points
2020-10-12T21:24:40.49+00:00

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
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,537 questions
0 comments No comments
{count} vote

Accepted answer
  1. Josh King 76 Reputation points
    2020-10-13T01:18:28.293+00:00

    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)

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.