CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Problems with Invoke-RestMethod and JSON Serialization of Nested Objects

👀 Views: 339 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
powershell json api PowerShell

After trying multiple solutions online, I still can't figure this out. I've looked through the documentation and I'm still confused about I've searched everywhere and can't find a clear answer. I'm having trouble using `Invoke-RestMethod` in PowerShell 7.3 to send a complex JSON payload to a REST API. The scenario arises when I attempt to serialize a nested object, and I keep getting the behavior message `want to serialize the nested property 'details'`. I've already tried using `ConvertTo-Json` with the `-Depth` parameter set to a larger value, but it doesn't seem to resolve the scenario. Here's the code I'm using: ```powershell $data = @{ name = 'Sample Item' type = 'example' details = @{ description = 'This is a nested object' created = (Get-Date) } } $jsonPayload = $data | ConvertTo-Json -Depth 5 $response = Invoke-RestMethod -Uri 'https://api.example.com/items' -Method Post -Body $jsonPayload -ContentType 'application/json' ``` When I run this, I get the behavior about serialization. I've also tried manually creating the JSON string like this: ```powershell $jsonPayload = '{"name":"Sample Item","type":"example","details":{"description":"This is a nested object","created":"' + (Get-Date).ToString('o') + '"}}' ``` However, I still face issues with date formatting once the API processes the request. The API expects the date in ISO 8601 format, but I need to seem to get the format right when constructing the JSON string. Any suggestions on how to properly serialize nested objects and format the date correctly for this API call? My development environment is Linux. My development environment is macOS. I'm working in a CentOS environment. Could this be a known issue? Hoping someone can shed some light on this.