Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows PowerShell parsing json - bracket vs dot

Using Windows PowerShell terminal for running a PS script.

I need to do (among the rest) some json file parsing. I ended up in a strange situation, here below posting a minimal example:

Json file:

{
  "mykey": "myvalue"
}

PS script:

$jsonContent = Get-Content "myfile.json" -Raw | ConvertFrom-Json
$jsonContent.GetType().FullName
$key = "mykey"
Write-Host "Using bracket notation: $($jsonContent[$key])"
Write-Host "Using dot notation: $($jsonContent.$key)"

Output:

System.Management.Automation.PSCustomObject
Using bracket notation:
Using dot notation: myvalue

I expected the exact opposite, bracket notation to work and dot notation to not work: what's happening here?

As an additional detail, $PSVersionTable.PSVersion returns 5.1.22621.4391.

like image 894
Giacomo Pirinoli Avatar asked Sep 15 '25 12:09

Giacomo Pirinoli


1 Answers

What happens is that indexing ([ ] index operator) works on objects that implement an indexer, and the default individual output from ConvertFrom-Json is a PSCustomObject (a custom object type in PowerShell). The properties of these objects are accessed via dot-notation by default which explains why $jsonContent.$key notation works fine. However, indexing would work by accessing the object's property collection, which does implement Item[string]:

$json = '{ "mykey": "myvalue" }' | ConvertFrom-Json
$key = 'mykey'
$json.psobject.Properties[$key].Value # myvalue

Perhaps, given the context of your question, you're likely coming from a different programming language and very likely you were expecting the output to be a dictionary type, which is totally possible if you're using PowerShell 7+ where you can tell ConvertFrom-Json that you want a dictionary type as output:

$json = '{ "mykey": "myvalue" }' | ConvertFrom-Json -AsHashtable
$key = 'mykey'
$json[$key] # myvalue

However, in Windows PowerShell 5.1 you're quite limited, you could achieve something similar by relying on the behind the scenes serializer used in this version:

Add-Type -AssemblyName System.Web.Extensions

$serializer = [Web.Script.Serialization.JavaScriptSerializer]::new()
$json = $serializer.Deserialize('{ "mykey": "myvalue" }', [hashtable])
$key = 'mykey'
$json[$key] # myvalue
like image 78
Santiago Squarzon Avatar answered Sep 17 '25 03:09

Santiago Squarzon