Last active
September 25, 2022 10:50
-
-
Save erelado/d89d879b985dbb8019a756a9fd15c282 to your computer and use it in GitHub Desktop.
Powershell function(s) to Flatten JSON to the expected Key/Value format used by Azure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Flatten-Json() { | |
Param( | |
[Parameter(Mandatory)] | |
[Object] | |
$JsonObject, | |
[Parameter(Mandatory = $False)] | |
[String] | |
$Delimiter = ":" | |
) | |
<# | |
.DESCRIPTION | |
Powershell function(s) to Flatten JSON to the expected Key/Value format used by Azure. | |
.PARAMETER JsonObject | |
Specifies the converted appsettings.json file. | |
.PARAMETER JsonObject | |
Specifies the delimiter between nested keys. Default is colon (':'). | |
.OUTPUTS | |
HashTable that contains the flattened json properties and values. | |
.EXAMPLE | |
$json = Get-Content '.\appSettings.json' -Raw | ConvertFrom-Json | |
PS> Flatten-Json $json | |
.LINK | |
https://docs.microsoft.com/en-us/azure/app-service/configure-common | |
#> | |
$HashTable = @{} | |
Flatten-JsonHelper -JsonObject $JsonObject -Delimiter $Delimiter -HashTable $HashTable | |
return $HashTable | |
} | |
Function Flatten-JsonHelper() { | |
Param( | |
[Parameter(Mandatory)] | |
[Object] | |
$JsonObject, | |
[Parameter(Mandatory)] | |
[String] | |
$Delimiter, | |
[Parameter(Mandatory)] | |
[HashTable] | |
$HashTable, | |
[Parameter(Mandatory = $False)] | |
[AllowEmptyString()] | |
[String] | |
$Prefix | |
) | |
if ($JsonObject -eq $null) { | |
return | |
} | |
[string] $pre = '' | |
foreach ($property in $JsonObject.PSObject.Properties) { | |
if ($property.MemberType -ne 'NoteProperty') { | |
continue | |
} | |
if ([string]::IsNullOrWhitespace($Prefix)) { | |
$pre = $property.Name | |
} | |
else { | |
$pre = "$($Prefix)$($Delimiter)$($property.Name)" | |
} | |
# Handle PSCustomObject | |
[string] $fullName = $property.Value.GetType().FullName | |
if ($fullName -eq 'System.Management.Automation.PSCustomObject') { | |
Flatten-JsonHelper -JsonObject $property.Value ` | |
-Delimiter $Delimiter ` | |
-Prefix $pre ` | |
-HashTable $HashTable | |
} | |
# Handle Object | |
elseif ($fullName -eq 'System.Object[]') { | |
$valArr = $property.Value | |
# Handle empty objects | |
if([string]::IsNullOrEmpty($valArr)) { | |
$HashTable.Add($pre, $property.Value) | |
} | |
else { | |
for ($i = 0; $i -lt $valArr.Length; $i++) { | |
Flatten-JsonHelper -JsonObject $valArr[$i] ` | |
-Delimiter $Delimiter ` | |
-Prefix "$($pre)$($Delimiter)$($i)" ` | |
-HashTable $HashTable | |
} | |
} | |
} | |
# Handle strings | |
else { | |
$HashTable.Add($pre, $property.Value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment