jsonpowershellconvertfrom-json

PowerShell: Get Key and Value from Json


I have the following Json:

{
    "variable1" : "variable2"
}

I won't know what the values for variable1 and variable2 are. I need to get them from the Json, presumably using two separate commands that use ConvertFrom-Json in some way. They should be returned in plaintext format, not any PSCustomObject or anything like that.


Solution

  • In PowerShell 7+ you can use ConvertFrom-Json -AsHashtable to convert your Json into a dictionary type object and from there you can access the .Keys and .Values properties.

    For example, given this Json:

    {
        "variable1": "variable2",
        "variable3": "variable4",
        "variable5": "variable6"
    }
    

    Assuming we have it the $json variable, we can do the following:

    $dict = ConvertFrom-Json $json -AsHashtable
    $dict
    
    # Name                           Value
    # ----                           -----
    # variable3                      variable4
    # variable5                      variable6
    # variable1                      variable2
    
    $dict.Keys
    
    # variable3
    # variable5
    # variable1
    
    $dict.Values
    
    # variable4
    # variable6
    # variable2
    

    In Windows PowerShell 5.1 as @Vivere notes in his comment, -AsHashTable isn't implemented, so to get them you have to access PSObject.Properties to get the property collection:

    $object = $json | ConvertFrom-Json
    $object.psobject.Properties.Name
    
    # variable1
    # variable3
    # variable5
    
    $object.psobject.Properties.Value
    
    # variable2
    # variable4
    # variable6