0

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" } } 
4
  • what version of powershell are you using? Commented Nov 24, 2022 at 15:51
  • PSVersion : 5.1.19041.1682 Commented Nov 24, 2022 at 15:53
  • ConvertFrom-Json. Commented Nov 24, 2022 at 16:00
  • Powershell 7 has name, value pairs with convertfrom-json -AsHashtable Commented Nov 24, 2022 at 16:41

3 Answers 3

1
$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 } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

4 Comments

I want to fetch ".isSecret" and ".value" for each item. Is there any way ?
I downvoted this answer because it gives the illusion of iterating over the members of the root object, but it doesn't actually
@MathiasR.Jessen fair, I've just realised that the input is an object rather than a list. will update.
Anyway, your answer satisfies my requirements. Thank you so much @TZHX .
0

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} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.