5

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
mklement0
  • 382,024
  • 64
  • 607
  • 775
Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102

1 Answers1

12

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

foreach ($obj in $json.PSObject.Properties) {
    $obj.Name
    $obj.Value
}
mklement0
  • 382,024
  • 64
  • 607
  • 775
Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102
  • 2
    Nice; for someone looking to extract the name paths and values of all leaf properties in an arbitrarily _nested_ JSON object, see [this answer](https://stackoverflow.com/a/64189034/45375). – mklement0 Sep 30 '21 at 20:11