Developer
Developer

Reputation: 769

Select a node from a JSON file that matches a property value

I am having a json object stored in a variable. From the json object, I want to fetch the node which matches a value. For example - an item having machineId 12.

My json looks like

{
    "items":  [
              {
                  "id":  "asdasd",
                  "machineId":  "12",
                  "placementGroup":  "",
                  "region":  "158",
                  "staticIp":  "",
                  "staticIpAction":  "",
                  "subnetIDs":  [

                                ]

              },
              {
                  "id":  "asdasd",
                  "machineId":  "43",
                  "placementGroup":  "",
                  "region":  "158",
                  "staticIp":  "",
                  "staticIpAction":  "",
                  "subnetIDs":  [

                                ]
              }
          ]
} 

Upvotes: 2

Views: 4210

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

Load the json using the Get-Content cmdlet and convert it to json using the ConvertFrom-Json cmdlet. Select the items node and filter it by the desired machineId using the Where-Object cmdlet:

Get-Content 'yourPathToYour.json' | 
    ConvertFrom-Json |
    Select-Object -ExpandProperty items |
    Where-Object machineId -eq 12

Output:

id             : asdasd
machineId      : 12
placementGroup : 
region         : 158
staticIp       : 
staticIpAction : 
subnetIDs      : {}

Upvotes: 3

Related Questions