CodexBloom - Programming Q&A Platform

PowerShell 7.3 - how to to Filter Objects by Nested Property Values from an API Response

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
PowerShell API JSON Filtering

I'm stuck on something that should probably be simple. I'm working on a personal project and I'm currently working with PowerShell 7.3 to interact with a REST API that returns a JSON response containing a list of users and their associated roles. The response structure looks something like this: ```json { "users": [ { "id": 1, "name": "Alice", "roles": [{ "type": "admin" }] }, { "id": 2, "name": "Bob", "roles": [{ "type": "user" }] }, { "id": 3, "name": "Charlie", "roles": [{ "type": "admin" }, { "type": "user" }] } ] } ``` I am trying to filter the list of users to only include those who have the role of "admin". I initially attempted to parse the JSON response and use `Where-Object` to filter, but I keep getting an behavior about accessing properties of a collection. Here's the code I've been using: ```powershell $response = Invoke-RestMethod -Uri "https://api.example.com/users" $admins = $response.users | Where-Object { $_.roles.type -eq 'admin' } ``` This code throws an behavior: ``` Method invocation failed because β€˜System.Object[]’ does not contain a method named β€˜type’. ``` I've also tried using `ForEach-Object` to iterate through `roles`, but the syntax gets messy and I couldn't find a clean way to check if any of the roles match "admin". Here's what that looks like: ```powershell $admins = $response.users | ForEach-Object { if ($_.roles | Where-Object { $_.type -eq 'admin' }) { $_ } } ``` This approach returns a list of `null` values, which is not what I expected. I want to get the user objects themselves, not just check their roles. How can I properly filter this nested property in PowerShell without running into these issues? Any advice or best practices for handling such nested structures in PowerShell would be greatly appreciated. Any ideas what could be causing this? For context: I'm using Powershell on Ubuntu. Am I missing something obvious?