Search code examples
jsonpowershellpowershell-4.0

Get value by the array element name in json


I'm not sure how to name these elements properly, it'll be easier just to show it. I have following JSON:

{
  "DEV": [
    {
      "GitEmail": "[email protected]"
    }
  ],
  "TEST": [
    {
      "GitEmail": "[email protected]"
    }
  ],
  "PROD": [
    {
      "GitEmail": "[email protected]"
    }
  ]
}  

I would like to get the "DEV" by providing it's email. How to implement that in powershell?


Solution

  • Something like below can help -

    PS> $json = '{
      "DEV": [
        {
          "GitEmail": "[email protected]"
        }
      ],
      "TEST": [
        {
          "GitEmail": "[email protected]"
        }
      ],
      "PROD": [
        {
          "GitEmail": "[email protected]"
        }
      ]
    }' | ConvertFrom-Json
    
    PS> ($json.psobject.Properties | ? {$_.Value -match "[email protected]"}).Name
    

    Depending on the email matches you can retrieve the environment names.