2

I have nested JSON file that looks like this

{name:{firstname: Joe, lastname: Bloggs}}

I convert from Json and save as a variable

$json = Get-Content -Path .\file.json -Raw | ConvertFrom-Json

I have a function that retrieves the property path and saves it to a variable

$firstname = "name.firstname"

Why does

$json.$firstname

not return Joe? How can I get Powershell to understand that it should be interpreted as

$json.name.firstname

instead of

$json."name.firstname"

Many thanks.

turnip98
  • 23
  • 3

1 Answers1

2

"name.firstname" is just a literal string, PowerShell doesn't know you are referring to the nested property firstname within the name property. You could expand the string via Invoke-Expression or $ExecutionContext.InvokeCommand.ExpandString(...) though that's better to be avoid whenever possible. Here is another way to do it by traversing the path:

$json = '{name:{firstname: "Joe", lastname: "Bloggs"}}' | ConvertFrom-Json
$path = 'name.firstname'

$path.Split('.') | & {
    begin { $targetObject = $json }
    process { $targetObject = $targetObject.$_ }
    end { $targetObject }
}
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37