Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 774
Stephen Walsh Avatar asked Oct 25 '25 19:10

Stephen Walsh


1 Answers

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
like image 161
Santiago Squarzon Avatar answered Oct 27 '25 15:10

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!