jsonpowershellconvertto-json

Powershell convertto-json gives a bad format


Hello I'm trying to use convertto-json to create a json file from another output and save it but I'm getting a bad json format

Here is my function


$output.value | ForEach-Object {
    "{"+"id"+':'+ $_.id+','+"outcome" +':'+ '"'+$_.results.outcome+'"'+','+"idtc"+':' +$_.testCaseReference.id  + "}"
} | ConvertTo-Json| Out-File -FilePath .\tfs.json



Here is the outcome of the tfs.json

[
    "{id:11431,outcome:\"passed\",idtc:70155}",
    "{id:11432,outcome:\"unspecified\",idtc:70156}",
    "{id:11433,outcome:\"failed\",idtc:70157}",
    "{id:11434,outcome:\"unspecified\",idtc:70158}"
]


Can anyone help why it does appear in that way instead of

[
    {"id":11431,"outcome":"passed","idtc":70155"},
    {"id":11432,"outcome":"unspecified","idtc":70156"},
    {"id":11433,"outcome":"failed","idtc":70157"},
    {"id":11434,"outcome":"unspecified","idtc":70158"}
]

Solution

  • The output you're receiving from ConvertTo-Json is pretty much expected, you're passing strings through the pipeline to the cmdlet hence it is returning a JSON array containing strings.

    What you should do instead, is construct PowerShell custom objects in your loop body and let the cmdlet convert those objects into JSON objects:

    $output.value | ForEach-Object {
        [pscustomobject]@{
            id      = $_.id
            outcome = $_.results.outcome
            idtc    = $_.testCaseReference.id
        }
    } | ConvertTo-Json | Out-File -FilePath .\tfs.json