CodexBloom - Programming Q&A Platform

PowerShell 7.3 - how to to parse JSON response from REST API with nested arrays

👀 Views: 42 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
PowerShell JSON API

I'm optimizing some code but I'm optimizing some code but I've been banging my head against this for hours... I'm working on a personal project and I'm working with issues when trying to parse a JSON response from a REST API in PowerShell 7.3. The API returns a complex JSON structure, including nested arrays, and I'm unable to access the specific data I need. The response looks something like this: ```json { "data": { "users": [ { "id": 1, "name": "Alice", "roles": [ "admin", "editor" ] }, { "id": 2, "name": "Bob", "roles": [ "viewer" ] } ] } } ``` I am trying to extract the names of the users who have the role "admin". Here's the code I've been using: ```powershell $response = Invoke-RestMethod -Uri "https://api.example.com/users" -Method Get $adminUsers = $response.data.users | Where-Object { $_.roles -contains "admin" } | Select-Object -ExpandProperty name $adminUsers ``` However, this results in an empty array. I've tried different approaches, including using `ConvertFrom-Json` to manually parse the JSON, but the same scenario continues. I also checked the API response, and it seems to be valid JSON. Is there something I'm missing in how I'm accessing the nested structures, or is there a different approach I should be using? Any help would be appreciated! I want to ensure that I'm following best practices for handling JSON in PowerShell as well. I'm working on a CLI tool that needs to handle this. I'd really appreciate any guidance on this. I'm on Ubuntu 20.04 using the latest version of Powershell. Has anyone else encountered this? Any feedback is welcome!