Home > Mobile >  Powershell: Reduce an array of JSON objects to an array of a single object field
Powershell: Reduce an array of JSON objects to an array of a single object field

Time:07-28

In Powershell, how do I reduce an array of JSON objects, like this below, into a simple String array of "Name"? I am NOT encountering this issue with a normal Json-Object (non-array).

[
    {
        "Name":"Name1",
        "Id": 3433
    },
    {
        "Name":"Name2",
        "Id": 5455
    }
]

Into this:

[
    "Name1", 
    "Name2"
]

Here is what I am trying to do. This code does NOT return an array; instead, it returns the value of the first item in the array.

function FindServiceBusNamespaces($ResourceGroup) {
    $toExecute = "az servicebus namespace list --resource-group ${ResourceGroup}"
    $response = GetAzResponseObject -Expression "$toExecute"
    $namespaceArray = @()
    foreach ($ns in $response)
    {
        $namespaceArray  = $ns | Select-Object -ExpandProperty id
    }
    return $namespaceArray
}

And same result with this:

function FindServiceBusNamespaces($ResourceGroup) {
    $toExecute = "az servicebus namespace list --resource-group ${ResourceGroup}"
    $response = GetAzResponseObject -Expression "$toExecute"
    $namespaceArray = @()
    foreach ($ns in $response)
    {
        $namespaceArray  = $ns.id
    }
    return $namespaceArray
}

CodePudding user response:

Without knowing what GetAzResponseObject returns, it's hard to diagnose your problem, but to answer the question at the start of your post:

$arr = @'
[
    {
        "Name":"Name1",
        "Id": 3433
    },
    {
        "Name":"Name2",
        "Id": 5455
    }
]
'@
$res = $arr | ConvertFrom-Json | ForEach-Object { $_.Name }

Write-Host (ConvertTo-Json @($res))

yields:

[
  "Name1",
  "Name2"
]
  • Related