Skip to content

Instantly share code, notes, and snippets.

@Tomamais
Last active January 7, 2026 16:27
Show Gist options
  • Select an option

  • Save Tomamais/a3d3ab2cc3736b5ebb39bba4ad87aa9e to your computer and use it in GitHub Desktop.

Select an option

Save Tomamais/a3d3ab2cc3736b5ebb39bba4ad87aa9e to your computer and use it in GitHub Desktop.
# 1. Configuration
$jsonInputPath = "C:\path\to\your\input.json"
$outputPath = "C:\path\to\your\output.txt"
# 2. Function to recursively flatten objects and arrays
function Flatten-JsonObject ($Object, $Prefix = "") {
$results = [ordered]@{}
foreach ($property in $Object.PSObject.Properties) {
# Construct the base key name (e.g., Person.Children)
$name = if ($Prefix -eq "") { $property.Name } else { "$Prefix.$($property.Name)" }
$value = $property.Value
# CASE 1: The value is a nested Object
if ($value -is [System.Management.Automation.PSCustomObject]) {
$subResults = Flatten-JsonObject -Object $value -Prefix $name
foreach ($key in $subResults.Keys) { $results[$key] = $subResults[$key] }
}
# CASE 2: The value is an Array/Collection
elseif ($value -is [System.Collections.IEnumerable] -and $value -isnot [string]) {
$index = 0
foreach ($item in $value) {
$arrayName = "$name[$index]"
# If array contains objects, recurse into them
if ($item -is [System.Management.Automation.PSCustomObject]) {
$subResults = Flatten-JsonObject -Object $item -Prefix $arrayName
foreach ($key in $subResults.Keys) { $results[$key] = $subResults[$key] }
} else {
# If array contains simple values (strings/ints)
$results[$arrayName] = $item
}
$index++
}
}
# CASE 3: The value is a "Leaf" (String, Int, etc.)
else {
$results[$name] = $value
}
}
return $results
}
# 3. Execution
try {
if (Test-Path $jsonInputPath) {
$json = Get-Content -Raw -Path $jsonInputPath | ConvertFrom-Json
$flattened = Flatten-JsonObject -Object $json
# Format as "Key: Value"
$outputStrings = $flattened.GetEnumerator() | ForEach-Object { "$($_.Key): $($_.Value)" }
$outputStrings | Out-File -FilePath $outputPath -Encoding utf8
$outputStrings # Display result
}
} catch {
Write-Error "Error: $($_.Exception.Message)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment