DEV Community

Prasanna Sridharan
Prasanna Sridharan

Posted on

2 1

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.

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs