Skip to content

Instantly share code, notes, and snippets.

@Wind010
Last active April 30, 2024 17:16
Show Gist options
  • Select an option

  • Save Wind010/8790760c6c32bdd61aa9c97b81d04f3a to your computer and use it in GitHub Desktop.

Select an option

Save Wind010/8790760c6c32bdd61aa9c97b81d04f3a to your computer and use it in GitHub Desktop.
Powershell functions to Flatten JSON to the expected Key/Value format used by Azure.
<#
.DESCRIPTION
Powershell functions to Flatten JSON to the expected Key/Value format used by Azure.
.OUTPUTS
HashTable that contains the flattened json properties and values.
.EXAMPLE USAGE
. /Flatten-Json.ps1 # Source the file to load the functions.
$json = Get-Content '.\appSettings.json' -Raw | ConvertFrom-Json
Flatten-Json $json
#>
Function Flatten-Json([object] $obj, [string] $prefix = '')
{
$ht = @{}
Helper $obj $prefix $ht
return $ht
}
Function Helper([object] $obj, [string] $prefix, [hashtable] $ht)
{
if ($obj -eq $null)
{
return
}
[string] $pre = ''
foreach($property in $obj.psobject.Properties)
{
if ($property.MemberType -ne 'NoteProperty')
{
continue
}
if ([string]::IsNullOrWhitespace($prefix))
{
$pre = $property.Name
}
else
{
$pre = "$($prefix)__$($property.Name)"
}
[string] $fullName = $property.Value.GetType().FullName
if ($fullName -eq 'System.Management.Automation.PSCustomObject')
{
Helper $property.Value $pre $ht
}
elseif ($fullName -eq 'System.Object[]')
{
$valArr = $property.Value
for($i=0; $i -lt $valArr.Length; $i++)
{
$ht.Add("$($pre)__$($i)", $valArr[$i])
}
}
else
{
$ht.Add($pre, $property.Value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment