Advanced JSON Objects Become CliXml

Product: PowerShell Universal
Version: 1.4.6

I’m having some trouble with my GET requests. When my function returns a complex hashtable, it gets
converted to CliXml instead of JSON for some reason? Here’s my endpoint:

> New-PSUEndpoint -Url "/logs/search" -Endpoint {
>     Search-Logs `
>         -searchTerm $searchTerm `
>         -pageSize $pageSize `
>         -startIndex $startIndex `
>         -StartDatetime $startDateTime `
>         -EndDateTime $endDateTime
> }

I’m getting output like this:

Am I meant to parse the CliXml somehow? How can I get it to JSON.

To Deserialize CliXml in most situations you can use the PSSerializer:

[System.Management.Automation.PSSerializer]::Deserialize($SerializedData.CliXml)

In your case, try assigning Search-Logs execution to a variable, then deserialize it

$SearchParameters = @{
    searchTerm    = $searchTerm 
    pageSize      = $pageSize 
    startIndex    = $startIndex 
    StartDatetime = $startDateTime 
    EndDateTime   = $endDateTime
}

$SerializedData = Search-Logs @SearchParameters
[System.Management.Automation.PSSerializer]::Deserialize($SerializedData.CliXml)

Also, I strongly recommend splatting over using backticks to create vertically organized code. Backticks have not really been a recommended practice for quite some time.

Thank you so much! This has had me a step from throwing my computer out the window!

1 Like

I’d also be curious as to what happens what you use ConvertTo-Json directly. While PSU should do that automatically, if you return a string, it should return it as JSON.

> New-PSUEndpoint -Url "/logs/search" -Endpoint {
>     Search-Logs `
>         -searchTerm $searchTerm `
>         -pageSize $pageSize `
>         -startIndex $startIndex `
>         -StartDatetime $startDateTime `
>         -EndDateTime $endDateTime | ConvertTo-Json 
> }
2 Likes

I hadn’t considered it but I assume PSU does this automatically.

@adam FWIW I’m working on some endpoint based stuff too where I’ve had to do this. Actually created custom endpoints to fetch UA Cache values for debugging.

This was actually the first approach I considered. For some reason, the output put one too many brackets around the content.

1 Like

Square or curly brackets? If square brackets, it enclosed it in an array which could mean the object being converted to json was technically an array.

When handling situations like this, where the data shouldn’t be an array (due to empty entries, etc…) I’ll do something like

$Items = $Items | Where-Object { -not [string]::IsNullOrWhitespace($PSItem)}
1 Like

It should do it automatically but just something to try.

It was encased in an extra set of curly braces but I’ve encountered this as well.

Ah, That is bizarre. I guess somewhere in the process prior to the conversion, it’s unnecessarily encapsulated inside another object :thinking: