2

I use PowerShell to parse the JSON file with array objects. My JSON file is like:

File Test.json

{
    "My Test Plan A": {
        "VariableA":"A",
        "VariableB":"B",
        "VariableC":"C",
        "VariableD":"D"
      },
    "My Test Plan B": {
        "VariableA":"E",
        "VariableB":"F",
        "VariableC":"G",
        "VariableD":"H"
    }
}

As you can see, there are two objects, My Test Plan A and My Test Plan B in my JSON file. And each object has the same variable name, but their values are different.

When the name of the array object is given, how can I get the variables of the corresponding array, so that I can get all the variables in the array for the next code to use?

After obtaining the corresponding array variable, how can the expression to obtain it in the following code be, like $(VariableA)?

Note:

The JSON file is written by myself. If it is not suitable, please modify it directly.

1 Answer 1

2

If you really need to use individual variables, use the intrinsic .psobject property to obtain the properties of the target object, and set variables based on them using Set-Variable:

# Specify the name of the target property
$name = 'My Test Plan B'

Get-Content -Raw file.json | 
  ConvertFrom-Json |
  ForEach-Object { 
    foreach ($p in $_.$name.psobject.Properties) { 
      Set-Variable $p.Name $p.Value
    }
  }

However, note that you could just use the target object as a whole and access its properties in lieu of defining multiple variables:

# Specify the name of the target property
$name = 'My Test Plan B'

$object = (Get-Content -Raw file.json | ConvertFrom-Json).$name

# Now you can use $object.VariableA, ... 
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to hear it, @Joy; my pleasure.

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.