I have a json file which has the below content. I want to iterate through each item (using foreach loop) in Powershell. How can I do it?
{
"abc": {
"isSecret": null,
"value": "'167401'"
},
"dar": {
"isSecret": null,
"value": "8980"
},
"hgt": {
"isSecret": null,
"value": "893240"
},
"newvar1": {
"isSecret": null,
"value": "newvalue1"
},
"var": {
"isSecret": null,
"value": "1230"
}
}
CodePudding user response:
$Data = $Json |ConvertFrom-Json
$Data.PSObject.Properties.Value
isSecret value
-------- -----
'167401'
8980
893240
newvalue1
1230
To iterate through the values:
$Data.PSObject.Properties.Value.ForEach{
Write-Host 'isSecret:' $_.isSecret
Write-Host 'Value:' $_.Value
}
CodePudding user response:
You can do something like:
$input = @'
<your input here>
'@
$json = $input | ConvertFrom-Json
foreach($item in $json.PSObject.Properties)
{
Write-Output $item.Name
Write-Output $item.Value.isSecret
Write-Output $item.Value.value
}
with your input, this gives me:
abc
'167401'
dar
8980
hgt
893240
newvar1
newvalue1
var
1230
as all your isSecret
values are null they don't show any content.
CodePudding user response:
Powershell 7 version with name,value pairs:
cat file.json | convertfrom-json -AsHashtable
Name Value
---- -----
hgt {isSecret, value}
newvar1 {isSecret, value}
dar {isSecret, value}
abc {isSecret, value}
var {isSecret, value}