Tom el Safadi
Tom el Safadi

Reputation: 6776

PowerShell iterate through json of key value pairs

I have a json file that maps alpha-2 codes to country names:

{
    "AF": "Afghanistan",
    "EG": "Ägypten",
    ...
}

I want to iterate over each key value pair to process the data. How would I be able to achieve that?

I tried the following but it always returns one big object that is not iterable in a key value manner:

$json = Get-Content -Path C:\countries.json | ConvertFrom-Json

Upvotes: 7

Views: 8970

Answers (1)

Tom el Safadi
Tom el Safadi

Reputation: 6776

I was able to achieve it like this, using the intrinsic .psobject property:

foreach ($obj in $json.PSObject.Properties) {
    $obj.Name
    $obj.Value
}

Upvotes: 16

Related Questions