Reputation: 137
I'm trying to get something working in Powershell where I can take a typical JSON file and restructure it so that it's represented in a sort of dot notation form.
As an input I'm reading in a JSON file. If, for example, the file looked something like:
{
"Logging": {
"MinLevel": {
"Default": "Information",
"Override": {
"Host": "Warning"
}
},
"Properties": {
"ApplicationName": "My App"
}
},
"ConnectionStrings": {
"DefaultConnection": "string"
}
}
... and from that, I'd like to end up with something flattened out but retaining the paths to the elements:
"Logging.MinLevel.Default" : "Information"
"Logging.MinLevel.Override.Host" : "Warning"
"Properties.ApplicationName" : "My App"
...
This is what I've been working towards and I think I'm sort of heading in the right direction but I've got pretty lost now. Here's my code:
function ConvertTo-DotNotation {
param(
[pscustomobject] $jsonObject,
[string] $splitWith = ":",
[string] $currentKey = ""
)
# Get all object members that we're interested in
$jsonObjectProperties = $jsonObject | Get-Member -MemberType NoteProperty
# Loop through each property and get the key and the corresponding value
foreach ($property in $jsonObjectProperties) {
$key = $property.Name
$value = $jsonObject.$key
$keyToPrepend = $key
# Check if the value is an object itself
if ($value -is [pscustomobject]) {
Write-Host "val is an object, need to recurse"
$nestedResult = ConvertTo-DotNotation -jsonObject $value -currentKey $keyToPrepend
# unsure what to set as result????
} else {
#unsure what to set as result ????
}
return $result
}
}
$appsettingsjson = Get-Content -Path ./AppSettingsJSON/regular_json_file.json | ConvertFrom-Json
$flattenedAppsettings = ConvertTo-DotNotation -jsonObject $appsettingsjson
Any pointers on this? Alternative approaches also welcome if I'm making a meal of this...
Thanks
Upvotes: 1
Views: 43