Given the two JSON examples
{
"A": {
"name": "noname",
"key": "nokey"
}
and then
{
"B": {
"property1": "value3",
"country": "australia"
}
}
Is it possible to create a Powershell script that could take either one of the JSON examples and loop through them without knowing any names/keys upfront? (Using Windows 2016)
Something similar to what is posted as an answer here How do I loop through or enumerate a JavaScript object?
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
Not working
Did try this, but it works only for the first level
$json = @"
{"A": {"property1": "value1", "property2": "value2"}, "B": {"property1":
"value3", "property2": "value4"}}
"@
$parsed = $json | ConvertFrom-Json
$parsed.PSObject.Properties | ForEach-Object {
$next = $_
$name = $_.Name
$value = $_.value
echo "$name = $value"
$next.PSObject.Properties | ForEach-Object {
$name = $_.Name
$value = $_.value
echo "Second level: $name = $value"
}
}