CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Retrieving and Parsing Nested JSON Objects from a File

👀 Views: 57 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
powershell json nested-objects

I'm working on a project and hit a roadblock. I'm working with PowerShell 7.3 and need to parse a nested JSON structure from a file, but I'm running into issues with accessing the nested properties. The JSON file looks like this: ```json { "employees": [ { "name": "John Doe", "details": { "age": 30, "department": "Sales" } }, { "name": "Jane Smith", "details": { "age": 25, "department": "Marketing" } } ] } ``` I am trying to retrieve the names and the corresponding ages of each employee. I first imported the JSON using `Get-Content` and `ConvertFrom-Json` like this: ```powershell $jsonData = Get-Content "C:\path\to\your\file.json" | ConvertFrom-Json ``` However, when I attempt to access the properties, I get an behavior: ```powershell $jsonData.employees.name ``` This results in the behavior message: `want to find an overload for "name" and the argument count: "0".` I tried using a `ForEach-Object` loop to iterate through the employees like so: ```powershell $jsonData.employees | ForEach-Object { $_.name, $_.details.age } ``` But this doesn't output the expected results, and instead, it just gives me the full objects. I also attempted to flatten the array to get a more readable output with the following: ```powershell $jsonData.employees | Select-Object name, @{Name='Age'; Expression={ $_.details.age }} ``` This doesn't seem to work either, and I end up with nothing displayed. Can anyone guide to understand how to correctly access and display the nested JSON properties? Any insights into what I'm doing wrong would be greatly appreciated!