CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Difficulty Passing Nested Objects to REST API with ConvertTo-Json

👀 Views: 48 💬 Answers: 1 📅 Created: 2025-06-08
powershell json api PowerShell

I'm testing a new approach and I'm converting an old project and I'm trying to send a nested PowerShell object to a REST API, but I'm running into issues with the JSON formatting. My object is structured with multiple levels of properties, and when I use `ConvertTo-Json`, the output doesn't seem to match the expected structure for the API. I’ve constructed my object as follows: ```powershell $person = [PSCustomObject]@{ Name = 'John Doe' Age = 30 Address = [PSCustomObject]@{ Street = '123 Main St' City = 'Anytown' State = 'CA' } PhoneNumbers = @( [PSCustomObject]@{ Type = 'Home'; Number = '555-1234' }, [PSCustomObject]@{ Type = 'Work'; Number = '555-5678' } ) } ``` When I execute `ConvertTo-Json -InputObject $person -Depth 3`, the output is not what I expect. Here is what I’m seeing: ```json { "Name": "John Doe", "Age": 30, "Address": { "Street": "123 Main St", "City": "Anytown", "State": "CA" }, "PhoneNumbers": [ { "Type": "Home", "Number": "555-1234" }, { "Type": "Work", "Number": "555-5678" } ] } ``` The result looks correct, but when I send this JSON to the API using `Invoke-RestMethod`, I receive an behavior: ``` HTTP 400 Bad Request: Invalid JSON format ``` I’ve double-checked the API documentation, and it seems like the structure should be correct. I've tried adjusting the `-Depth` parameter and even manually constructing the JSON string using `@{}` syntax, but I still run into issues. Is there something I’m missing regarding how to properly format the JSON or how to structure the object before converting it? Any insights would be greatly appreciated! How would you solve this? I'm using Powershell latest in this project. Cheers for any assistance!