Reputation: 945
I use PowerShell to parse the JSON file with array objects. My JSON file is like:
{
"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.
Upvotes: 2
Views: 131
Reputation: 438178
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, ...
Upvotes: 2