0

I am trying to get the key value from object inside JSON array, please also suggest if I need to change my RuleId key structure, below is the output I want

rule = 1300
rulevalue = false
    
rule = 1304
rulevalue = true

JSON file

{
    "Rule": [{
        "MPName": "ManagementPackProject",
        "Request": "Apply",
        "Category": "Rule",
        "RuleId": {
            "1300": "false",
            "1304": "true"
        }
    }]
}

PowerShell

$Content = Get-Content -Raw -Path "C:\temp\Rule.json" | ConvertFrom-Json -ErrorAction Stop
$Content = $Content.Rule | Where-Object { $_.Request -eq "Apply" }

foreach($item in $Content.RuleId)
{
    rule = $item.key
    rulevalue = $item.value
    
    process...
}

1 Answer 1

3

Are you after something like this?

$JSON = @'
    {
        "Rule": [{
            "MPName": "ManagementPackProject",
            "Request": "Apply",
            "Category": "Rule",
            "RuleId": {
                "1300": "false",
                "1304": "true"
            }
        }]
    }
'@

$Content = $JSON | ConvertFrom-Json
$Content = $Content.Rule | Where-Object Request -eq 'Apply'

$Output = foreach( $Rule in $Content.RuleId.psobject.Properties ) {
    [PSCustomObject]@{
        Rule = $Rule.Name
        RuleValue = $Rule.Value
    }
}
$Output | Format-List

Output:

Rule      : 1300
RuleValue : false

Rule      : 1304
RuleValue : true
Sign up to request clarification or add additional context in comments.

4 Comments

Hi @PMental just 1 thing how to count how many properties there $Content.RuleId.psobject.Properties.Length not working
Force it into an array like this @($Content.RuleId.psobject.Properties).Length
@PMental Is there a way to collect and assign 'Rule' and 'RuleValue' values to a variable and later use it ? I found your answer useful but it is only printing output.
@user1557960 That's already there in the script, they're all stored in the $Output variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.