Functions/Get-JsonStringMaximumDepth.ps1
<#
.SYNOPSIS This function returns the maximum depth within a JSON string. #> function Get-JsonStringMaximumDepth { [CmdletBinding()] [OutputType([Int32])] param ( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$jsonString ) # Validate the JSON string try { ConvertFrom-Json $jsonString | Out-Null } catch { Write-Error "JSON string is not valid.`r`n$($_.Exception.Message)" return $null } # Iterate through the string to find the maximum depth $maximumDepth = -1 $currentDepth = 0 foreach ($char in $jsonString.ToCharArray()) { # Open brackets increases the depth if ($char -in @('[', '{')) { ++$currentDepth $maximumDepth = ($maximumDepth, $currentDepth | Measure-Object -Maximum).Maximum } # Close brackets decreases the depth elseif ($char -in @(']', '}')) { --$currentDepth } } # Invalid depth if ($maximumDepth -eq -1) { return $null } # Return the maximum depth return $maximumDepth } |