1

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').

3
  • $data.Tours|? Code -eq r|% Tournaments Commented Jun 20, 2016 at 17:47
  • @PetSerAl, thanks! But is it possible to refer to 'Tournaments' directly by using JSON notation and specifying 'r' value for the 'Code' under 'Tour'? Commented Jun 20, 2016 at 18:36
  • refer to 'Tournaments' directly by using JSON notation Is JSON include some query language like XPath for XML? I am not aware of such thing. Commented Jun 20, 2016 at 18:45

1 Answer 1

2

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 }}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! If I pipe your command to ForEach-Object, will I be able to refer to .Code value from Where-Object? For example, if I need to concatenate 'Code' with 'Tournaments.Number' within ForEach-Object code block.
Just updated my answer which some code that should do this for you
Excellent! Thanks, Chris!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.