0
Follow
9
View

Powershell getting nested values: Can you use ConvertFrom-Json for nested Values

derek_forever 注册会员
2022-12-07 01:22

In order (i.e. those properties that contain primitive JSON values as opposed to containing nested objects with properties and / or arrays), you need to the object graph:

Find helper function Get-LeafProperty below; assuming you have already defined it, you can call it as follows:

@'
  {
    "Location": "EU",
    "Country": {
      "City": "xxx",
      "Town": "xxy"
    },
    "Transport": {
      "Train": "xxz"
    }
  }
'@ | 
  ConvertFrom-Json |
  Get-LeafProperty

Output (the display formatting of [pscustomobject] instances with .Name and .Value properties representing all the leaf properties):

Name     Value
----     -----
Location EU
City     xxx
Town     xxy
Train    xxz

:

# Walks a potentially nested [pscustomobject] graph
# as returned by ConvertFrom-Json and outputs all
# leaf properties as name-value custom objects.
function Get-LeafProperty {
  param([Parameter(ValueFromPipeline)] [object] $InputObject)
  process {   
    if ($InputObject -is [array]) { # array as single input object -> recurse
      foreach ($o in $InputObject) { Get-LeafProperty $o }
    }
    else { 
      # Assumed to be a (potentially nested) [pscustomobject] instance:
      # Recursively process its properties.
      foreach ($p in $InputObject.psobject.properties) {
        if ($p.Value -is [array]) { # array -> recurse
          foreach ($o in $p.Value) { Get-LeafProperty $o }
        } elseif ($p.Value -is [System.Management.Automation.PSCustomObject] ) { # nested [pscustomobject] -> recurse
          Get-LeafProperty $p.Value
        } else { # leaf property reached -> output name-value pair
          [pscustomobject] @{ Name = $p.Name; Value = $p.Value }
        }
      }
    }
  }
}

Note: A variant of this function that outputs property name paths (e.g. Country.City) instead of just their names (e.g. City) can be found in this answer.

About the Author

Question Info

Publish Time
2022-12-07 01:22
Update Time
2022-12-07 01:22