0

Need help with how I can explicitly list the key names and its values for the below JSON using powershell.

    {
    "Data": {
        "OS_Support": {
            "SupportedOS": [
                "Microsoft Windows 10",
                "Microsoft Windows 11"
            ]
        },
        "MinFreeDiskSpace": {
            "SupportedDisk": 20
        },
        "MinMemorySize": {
            "SupportedMemory": 8
        },
        "App": {
            "Name": "Notepad",
            "Version": "1.2.3.4"
        }
    }
}

E.g. looking for output as below. Want to list the output with the last key name and its value.

SupportedOS      Microsoft Windows 10, Microsoft Windows 11
SupportedDisk    20
SupportedMemory  8
Name             Notepad
Version          1.2.3.4

I am trying to use below but it doesnt help. Any pointers would be really helpful,

(Get-Content -Path "JsonPath" | ConvertFrom-Json ).Data | Get-Member | Where-Object { $_.MemberType -match "Property" }
Dhillli4u
  • 117
  • 12

1 Answers1

0

Extensive code but should be able to handle Jsons with different structures and output objects using the deepest key value pair as its properties.

$queue = [System.Collections.Generic.Queue[object]]::new()
$result = Get-Content test.json | ConvertFrom-Json | ForEach-Object {
    $queue.Enqueue($_)
    $tmp = [ordered]@{}

    while ($queue.Count) {
        foreach ($pso in $queue.Dequeue().PSObject.Properties) {
            $value = $pso.Value
            $isCollection = $false

            if ($value -is [System.Collections.ICollection]) {
                $isCollection = $true
                if ($value[0] -is [System.Management.Automation.PSCustomObject]) {
                    foreach ($item in $value) {
                        $queue.Enqueue($item)
                    }
                    continue
                }
            }

            if ($value -is [System.Management.Automation.PSCustomObject]) {
                $queue.Enqueue($value)
                continue
            }

            if ($isCollection) {
                $value = $value -join ', '
            }

            $tmp[$pso.Name] = $value
        }
    }

    [pscustomobject] $tmp
}

$result | Format-Table

Using the Json in your question the result would be:

SupportedOS                                SupportedDisk SupportedMemory Name    Version
-----------                                ------------- --------------- ----    -------
Microsoft Windows 10, Microsoft Windows 11            20               8 Notepad 1.2.3.4
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37