How to Dynamically Access JSON Properties in PowerShell?

0
0
Asked By CuriousCoder97 On

I'm working on a script that pulls asset data from our CMDB via an API, and I'm having trouble accessing dynamic properties in the JSON response. Specifically, I'm trying to retrieve a field named 'Datavolume_XXXXXXXXX', where the 'XXXXXXXXX' part changes depending on the device type. I've already set this variable earlier in my script as $bodyid.

For example, I have a hard-coded device field at $targetinfojson.asset.type_fields.datavolume_1234. So when I try to access the property using a dynamic string, like $target=$targetinfojson.asset.type_fields.datavolume_$bodyid, I'm getting null instead of the expected value "0-100". When I use this in the terminal, it throws an error about an unexpected token in the payload. Can someone guide me on how to retrieve this dynamically?

3 Answers

Answered By ScriptGeniusX On

You might want to check the properties of your JSON object all the way down. If you have a structure like `$json.data_file.thing_123`, that's how you'll access it. But if there’s a property named "data_file.thing_123", you'll need quotes: `$json."data_file.thing_123"`. Use `Get-Member` to explore the properties of your objects to find out what exactly you're working with!

Answered By PowerShellNinja On

PowerShell's dot notation does not allow for dynamic property names using variables. Instead, use square bracket notation! Like this:

```powershell
$fieldName = "datavolume_$bodyid"
$data = $targetinfojson.asset.type_fields[$fieldName]
```
This way, PowerShell should evaluate the variable correctly.

CuriousCoder97 -

I tried using the brackets like suggested, but it threw a syntax error in VSCode. I was aiming for a one-liner, but it seems that’s not feasible. My current attempt is this:

```powershell
$dvid="data_volume_$bodyid"
$targetdata=$targetinfoJSON.asset.type_fields.$dvid
```
Thanks for the help!

Answered By TechWhiz123 On

You could approach this in a few ways. For instance, try defining your dynamic property like this:

```powershell
[string]$number = '1234'
$targetinfoJSON = @{
asset = @{
type_fields = @{
('datavolume_{0}' -f $number) = 'someValue'
}
}
} | ConvertTo-Json | ConvertFrom-Json
```
Then you can access the property either using literal property names or dynamic ones by wrapping it in double quotes.

However, make sure you've got the right structure for your JSON object!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.