CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Trouble with Filtering Nested Objects in JSON Arrays

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-18
powershell json filtering PowerShell

I'm integrating two systems and I'm relatively new to this, so bear with me... I'm working with PowerShell 7.3 and am trying to filter through a nested JSON structure to extract specific values. The JSON structure looks something like this: ```json { "users": [ { "id": 1, "name": "Alice", "details": { "age": 30, "city": "New York" } }, { "id": 2, "name": "Bob", "details": { "age": 25, "city": "San Francisco" } } ] } ``` I want to filter out users who are older than 28 and get their names and cities. I've tried using the `ConvertFrom-Json` cmdlet combined with `Where-Object`, but I'm running into issues with accessing the nested properties. Here’s what I’ve attempted: ```powershell $jsonContent = Get-Content -Path "path/to/your/file.json" -Raw | ConvertFrom-Json $filteredUsers = $jsonContent.users | Where-Object { $_.details.age -gt 28 } | Select-Object name, @{Name='City'; Expression={ $_.details.city }} $filteredUsers ``` This code runs without errors, but it returns an empty array, even though I can see that there are users older than 28 in the original JSON. I suspect it might be an scenario with how I'm accessing the nested properties. Can anyone guide to figure out what I might be doing wrong? I also checked the structure of the JSON after conversion and it seems to be correct, so I'm a bit stumped as to why the filtering isn't giving me the expected results. My development environment is Ubuntu. What am I doing wrong? I appreciate any insights! This is happening in both development and production on Windows 10.