Assert-JsonValidity.psm1

<#
.SYNOPSIS
    Takes a JSON object and or string and verifies its valid and converts it to a usable object

.DESCRIPTION
    Takes a JSON object and or string and verifies its valid and converts it to a usable object
    This was created in order to fix an issue with Azure Automation Accounts which have a known
    bug with Powershell 7.1 and runbooks which are called via WebHooks. This fixes the broken JSON
    that is passed to it (such as $RecoveryPlanContext Variablepassed by ASR)

.NOTES
    ┌─┐┬─┐┌─┐┌┬┐┌─┐┬─┐┌─┐ ┌┬┐┌─┐┌─┐┬ ┬┌┐┌┌─┐┬ ┌─┐┌─┐┬┌─┐┌─┐ ┬ ┬ ┌─┐
    ├─┘├┬┘│ │ │ ├┤ ├┬┘├─┤ │ ├┤ │ ├─┤││││ ││ │ ││ ┬│├┤ └─┐ │ │ │
    ┴ ┴└─└─┘ ┴ └─┘┴└─┴ ┴ ┴ └─┘└─┘┴ ┴┘└┘└─┘┴─┘└─┘└─┘┴└─┘└─┘ ┴─┘┴─┘└─┘
    # Copyright (c) Protera Technologies LLC. All rights reserved. #

    Author Cody.Diehl|Protera Technologies LLC
    Email c.diehl@protera.com
    Create 05-20-2022 13:31:20
    Modify 05-26-2022 21:31:19
    Version v0.9.1

    05-20-2022 - initial function creation for gzip decompress base64 decoding - Cody Diehl
    05-26-2022 - Configured as a Module to post on PowerShell Gallery for Azure Automation - Cody Diehl
#>


# Validate JSON Parameter passed to the runbook to ensure there is no errors
function Assert-JsonValidity() {
  # Workaround for Powershell 7.1 as there is known issue causing Webhook invocation to break JSON, so lets fix it without breaking it in future
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelinebyPropertyName = $True)]
    $Json
  )

  # Checks if the content is valid json already, or if not then will run string replacement on it
  $ValidateJson = $Json | Test-Json -ErrorAction SilentlyContinue
  if (-Not ($ValidateJson)) {
    $Json = $Json -replace ',', '","'   `
                  -replace ':', '":"'   `
                  -replace '}', '"}'    `
                  -replace '{', '{"'    `
                  -replace ':"{', ':{'  `
                  -replace '"}', '}'    `
                  -replace '\/}', '/"}' `
                  -replace '}",', '},'

    # after string replace runs to check if its valid now if not then either another missing replace is needed or its not JSON
    $ValidateJson = $Json | Test-Json -ErrorAction SilentlyContinue
    if ($ValidateJson) {

      Write-Verbose -Message "`$Json is valid JSON"
      Write-Verbose -Message "`$Json:`n$Json`n"

      $Json = $Json | ConvertFrom-Json
      return $Json
    }
    else {
      Write-Error -Message "`$Json is not a valid, ensure there is no missing replacements still needed.`n`n`$Json:`n$Json`n`nError:`n$_" -ErrorAction Stop
    }
  }

  # Test returned valid json so ConvertFrom-Json makes it a usable object same as it was in 5.1
  else {
    Write-Verbose -Message "`$Json is Valid JSON and converting to an Object"
    $Json = $Json | ConvertFrom-Json
    return $Json
  }

}

Export-ModuleMember -Function Assert-JsonValidity