Conertto-Json - weird output

Hi,

Im trying to build a powershell module, that allows me to ship logs to a humio endpoint.
But im having issues with converting my data to JSON:


[array]$Events = @()
$JsonBody = @(
    @{
        tags   = @{
            host       = $env:COMPUTERNAME
            ModuleType = "SQLBaseline2"
        }
        Events = @{
            timestamp  = get-date
            attributes = @{
                StatusCode    = "Info"
                RequestMethod = "GET"
                PSRunbook     = "Runbook123"
                SQLInstance   = "instance123"
                CustomMessage = "wohoo"
            }
        }
    }
) | ConvertTo-Json -Depth 10
$JsonBody
Invoke-RestMethod -Method Post -Uri "http://redacted.humio.endpoint/api/v1/ingest/humio-structured" -Headers $HumioHeader -Body $JsonBody -SkipCertificateCheck -ContentType "application/json"

I managed to get it working with this code instead, but i would really like to know what the reason is, why the first example isnt working.


$Events = @{
    timestamp  = get-date
    attributes = @{
        StatusCode    = "Info"
        RequestMethod = "GET"
        PSRunbook     = "Runbook123"
        SQLInstance   = "instance123"
        CustomMessage = "wohoo"
    }
}

$JsonBody = ConvertTo-Json -InputObject @(
    @{
        tags   = @{
            host       = $env:COMPUTERNAME
            ModuleType = "SQLBaseline2"
        }
        events = $Events
    }    
) -Depth 10
$JsonBody
Invoke-RestMethod -Method Post -Uri "http://redacted.humio.endpoint/api/v1/ingest/humio-structured" -Headers $HumioHeader -Body $JsonBody -SkipCertificateCheck -ContentType "application/json"

Can you explain to me why? :slight_smile:

I’m not completely sure but I think it is because you only pass one element through the pipeline. If you pass two or more it works as expected. Using the method with -InputObject you pass an explicit array.

This may be a workaround:

$JsonBodyInput = @(
    @{
        tags   = @{
            host       = $env:COMPUTERNAME
            ModuleType = "SQLBaseline2"
        }
        Events = @{
            timestamp  = get-date
            attributes = @{
                StatusCode    = "Info"
                RequestMethod = "GET"
                PSRunbook     = "Runbook123"
                SQLInstance   = "instance123"
                CustomMessage = "wohoo"
            }
        }
    } 
) 

$JSONBodyOutput = ConvertTo-Json -Depth 10 -InputObject $JsonBodyInput

Hi Olaf,

Thanks for the update. Ive just tested it, and im afraid it dont work.
To me it looks almost identical to my first example.

What do you do differently? For me the output of my code suggestion looks exactly the same like the output your second code snippet provides.

Could you share the desired output? (formatted as code, please)