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 a string to the cmdlet hence it is returning a string as JSON.

    Try this instead:

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