Roka545
Roka545

Reputation: 3636

Access Properties and Keys within JSON using PowerShell

I have a PowerShell script and would like to access a nested key. Here is my JSON:

{
    "name": "versions.json",
    "versions": {
        "1.0.0": {
            "Component1": "1.0.0",
            "Component2": "1.0.0",
            "Component3": "1.0.0"
        },
        "2.0.0": {
            "Component1": "2.0.0",
            "Component2": "2.0.0",
            "Component3": "2.0.0"
        }
    }
}

I'm unsure of how to access the values within each version (1.0.0 and 2.0.0). I know I get the property name for each "version" by using:

($json.versions.PSobject.Properties) | ForEach-Object {
    "Data: $($_.Name)"
}

But how do I iterate through each of a "version" objects properties and view its value, i.e. how do I check what is contained within "1.0.0"? For "1.0.0" I would expect to see

"Component1" at 1.0.0
"Component2" at 1.0.0
"Component3" at 1.0.0

Upvotes: 1

Views: 3417

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200493

Do the same you're doing for versions for the values of its properties:

$json.versions.PSobject.Properties | ForEach-Object {
    "Data: $($_.Name)"
    $_.Value.PSobject.Properties | ForEach-Object {
        '"{0}" at {1}' -f $_.Name, $_.Value
    }
}

Upvotes: 2

Related Questions