YMM
YMM

Reputation: 702

Accessing values in a PS custom object property generated from JSON

For a JSON like this:

{
"Tours": [{
    "Code": "r",
    "Name": "Tour 1",
    "Tournaments": [{
        "Number": "464",
        "Title": "Open Tournament 1"
    },
    {
        "Number": "047",
        "Title": "Open Tournament 2"
    }]
},
{
    "Code": "s",
    "Name": "Tour 2",
    "Tournaments": [{
        "Number": "524",
        "Title": "Tournament 3"
    },
    {
        "Number": "009",
        "Title": "Tournament 4"
    }]
}]
}

when converted to a PS custom object and saved in $data variable, I can access values under 'Tournaments' for specific 'Tours' like this:

$data.Tours[0].Tournaments
$data.Tours[1].Tournaments

But, is it possible to access 'Tournaments' properties and values by specifying 'Code' or 'Name' values under 'Tours'? Something like that, maybe:

$data.Tours.Code['r'].Tournaments

Actually, in a PS script I want to filter data by 'Code' under 'Tours' and get underlying 'Tournaments' (get 'Tournaments' for specific 'Code' of the 'Tours').

Upvotes: 1

Views: 1576

Answers (1)

Chris Barber
Chris Barber

Reputation: 513

You would need to do something like:

$data.Tours | Where-Object { $_.Code -eq 'r' } | Select-Object -ExpandProperty 'Tournaments'

To get the list of concatenated codes and tournament numbers (where the code is "r") you could do:

$data.Tours | Where-Object { $_.Code -eq 'r' } | ForEach-Object { $Code = $_.Code; $_.Tournaments | ForEach-Object { $Code + $_.Number }}

Upvotes: 2

Related Questions