1

I am working to build a way to iterate through all the key value pairs of a PSObject that was created by using ConvertFrom-Json.

To do this, I need a way to know if a given PSObject has one or more children.

So, given the following JSON:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

I run this code:

$settings = Get-Content -Raw $pathToFile | ConvertFrom-Json
foreach ($base in $settings.PSObject.Properties) 
{
    if ($base.HasChildren -eq $true)
    {
        // Iterate Deeper
    }
}

When I am on the "Logging" node, $base has true for HasChildren but AllowedHosts has false.

Obviously, there is no such method of HasChildren, so this would not work. But I am wondering if there is a a way to find this out?

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • 2
    you can check if `$base.Value -is [System.Management.Automation.PSCustomObject]` // is this just for coding exercise or are you looking to traverse a json programmatically ? Note that this has been answered before – Santiago Squarzon Jan 24 '23 at 00:48
  • Hmm, another take aside from Santiagos is perhaps parsing the raw text: `$settings = ($rawJson = Get-Content -Raw $pathToFile) | ConvertFrom-Json`. Then you could convert it to a char array counting the openings: `$rawJson.ToCharArray().Where{$_ -match '\[|{'}.Count`. – Abraham Zinala Jan 24 '23 at 00:50
  • 1
    In addition to @mklement0 correct answer, you might also consider the [`-AsHashTable`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-json#-ashashtable) parameter (introduced in PowerShell 6.0): `(ConvertFrom-Json $Json -AsHashTable).Values |Where-Object { $_ -is [HashTable] }` or (considering your background), fall back on the [Newtonsoft.Json.Linq nemespace](https://www.newtonsoft.com/json/help/html/n_newtonsoft_json_linq.htm) to iterate through the objects, see: https://stackoverflow.com/a/74352656/1701026 – iRon Jan 24 '23 at 07:44

1 Answers1

1

What ConvertFrom-Json outputs is a [pscustomobject] graph, so you can indeed test properties of that graph enumerated via the intrinsic psobject property for being instances of that type using -is, the type(-inheritance) / interface test operator, as Santiago Squarzon suggests:

foreach ($base in $settings.PSObject.Properties) {
    if ($base.Value -is [pscustomobject]) {
        # Iterate Deeper
    }
}

Note:

mklement0
  • 382,024
  • 64
  • 607
  • 775