DEV Community

Prasanna Sridharan
Prasanna Sridharan

Posted on

Read Json property values using dot notation

Sometime we want to read a value of property nested deep within the json. This simple code helps get the value

Lets say the json looks like this:

{
  "level1-1": {
    "level2-1": "value2",
    "level2-2": {
      "level3-1": "value3" 
    }
  },
  "level1-2": "value1-2"
}

Enter fullscreen mode Exit fullscreen mode

Then to read value3, we can use syntax like level1-1.level2-2.level3-1.

This code is PowerShell can be used.

function getValue($obj, $fullkey) {
    $ks1, $ks2 = $fullkey.Split('.', 2)
    # Technique to read a property from PSCustomObject
    $props = $obj | Get-Member | Where-Object MemberType -Like 'NoteProperty'
    foreach($p in $props)
    {
        if($p.name -eq $ks1)
        {
            # Get the value of the property name
            $val = $obj | Select-Object -ExpandProperty $p.name
            #if not reached last key yet, go recursive.
            if($ks2 -ne $null){
                return getValue -obj $val -keylist $ks2
            } 
            return $val
        }
    }

    return $null;
}
Enter fullscreen mode Exit fullscreen mode

Usage:

$json = ConvertFrom-JSON '{"level1-1": { "level2-1": "value2", "level2-2": {"level3-1": "value3"}}, "level1-2":"value1-2"}'

$key = 'level1-1.level2-2.level3-1';
$res = getValue -obj $json -keylist $key
Write-Host "Key: " $key ", Value: " $res
Enter fullscreen mode Exit fullscreen mode

The response would look like:
Response with keys and values

In another blog will try to show a scenario with arrays and indices.

Happy coding.

Top comments (0)