Home > other >  Conditional parsing of array objects of json files with powershell
Conditional parsing of array objects of json files with powershell

Time:11-06

I use powershell to parse the Json file with array objects, my Json file like:

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.

Now what I want to achieve is, when the name of the array object is given, to 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 is, like $(VariableA)?

Note:

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

CodePudding user response:

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, ... 
  • Related