PowerShell 7.3 - guide with Converting CSV to JSON with Nested Objects for API Consumption
I'm working with a scenario while trying to convert a CSV file into a nested JSON structure that can be consumed by a REST API. My goal is to read a CSV file, transform the data into a specific hierarchical format, and then output it as JSON. However, I've encountered an scenario where the output JSON does not properly reflect the nested structure I need. Hereβs the structure of my CSV: ``` Name, Age, Address_Street, Address_City, Address_State John Doe, 30, 123 Elm St, Springfield, IL Jane Smith, 25, 456 Oak St, Springfield, IL ``` I want the resulting JSON to look like this: ```json [ { "Name": "John Doe", "Age": 30, "Address": { "Street": "123 Elm St", "City": "Springfield", "State": "IL" } }, { "Name": "Jane Smith", "Age": 25, "Address": { "Street": "456 Oak St", "City": "Springfield", "State": "IL" } } ] ``` Iβve attempted to use the following PowerShell script: ```powershell $csvData = Import-Csv -Path "data.csv" $jsonData = $csvData | ForEach-Object { [PSCustomObject]@{ Name = $_.Name Age = [int]$_.Age Address = [PSCustomObject]@{ Street = $_.Address_Street City = $_.Address_City State = $_.Address_State } } } $jsonOutput = $jsonData | ConvertTo-Json -Depth 3 $jsonOutput | Out-File -FilePath "output.json" ``` However, when I run this script, the resulting JSON output is not formatted correctly. Specifically, the nested Address object comes out as a flat structure instead of nested. I receive an behavior message saying `Maximum depth exceeded in JSON serialization` when trying to increase the `-Depth` parameter. I've tried adjusting the `-Depth` parameter in the `ConvertTo-Json` cmdlet, but it seems to not resolve the scenario. Can anyone suggest what I might be doing wrong or how I can correctly structure the output to achieve the desired nested JSON format? Any insights or alternative approaches would be greatly appreciated!