wanted to traverse in json body and get values from list using powershell.
json file
{
"TopicPropProfiles": [
{
"TP1":{
"enable-duplicate-detection": true,
"enable-batched-operations": true,
"enable-ordering": true
},
"TP2":{
"max-delivery-count": 3,
"enable-batched-operations": true
}
}
],
"SubPropProfiles": [
{
"SP1":{
"enable-duplicate-detection": true,
"max-size": 1024
},
"SP2":{
"max-delivery-count": 3,
"enable-batched-operations": true,
"enable-session": false
}
}
],
"Topics":[
{
"TopicName": "topic1",
"SubNames": ["sub1","sub2","sub3"],
"TopicPropertyProfile": "TP1",
"SubPropertyProfile": "SP2"
},
{
"TopicName": "topic2",
"SubNames": ["sub4","sub5","sub6"],
"TopicPropertyProfile": "TP2",
"SubPropertyProfile": "SP1"
}
]
}
powershell --getting file from somepath($profilepath)
$profilejson = Get-Content -Raw $profilePath | ConvertFrom-Json;
$profileObject = [PSCustomObject]$profilejson;
$TopicProps=$profileObject.TopicPropProfiles.**TP1**;
Write-Host $TopicProps.'enable-duplicate-detection'
Wanted to get fields values under TP1 or TP2(this value will be passed dynamically through some other parameters). Is above syntax/approach correct?
CodePudding user response:
To get the values of specific keys, you can use the dot notation. Example :
$json = Get-Content -Raw .\json.json | ConvertFrom-Json
$json.TopicPropProfiles
To see the content of TP1
$json.TopicPropProfiles.TP1
To get get the value of your first key/value pair inside TP1
$json.TopicPropProfiles.TP1.'enable-batched-operations'
Like this, you'll get the object returned. If you want the values, you need to use Select-Object
$json.TopicPropProfiles.TP1 |Select-Object -ExpandProperty TP1
CodePudding user response:
I have reproduced in my environment and I got expected results as below:
$result = Get-Content "Path" -raw | ConvertFrom-Json
$result.TopicPropProfiles.TP1
what if TP1 if also in some var like $profile=TP1 then?
$result = Get-Content "path" -raw | ConvertFrom-Json
$profile='TP1'
$result.TopicPropProfiles[0].$profile