Andreas_Lng
Andreas_Lng

Reputation: 1199

Using MS PowerShell ISE to query json data

I have a text file containing json data and looks like this:

{ 
  "field1":"value1",
  "field2": [
      { 
         "subfield1": "subvalue",
         "subfield2": []
      },
      { 
         "subfield1": "subvalue2",
         "subfield2": [ "string1", "string2", "...", "stringN" ]
      }
  ]
}

I want to get the count of objects contained in field2, where subfield2 is empty.

I tried it this way to get all objects where subfield2 is empty:

$datas = Get-Content -Path .\data
$json = $datas | ConvertFrom-Json
$json.field2 | Select-Object subfield2 | where subfield2 -Match ".*\[\].*"

Executing this results in no output. Using -EQ or -Like doesn't work either.

Upvotes: 0

Views: 173

Answers (1)

Kory Gill
Kory Gill

Reputation: 7163

Probably many other ways. This is one.

@($json.field2 | Where-Object {$($_.subfield2) -eq $null}).Count

Make $_.subfield2 a string with $($_.subfield2). Check string for $null.

Upvotes: 3

Related Questions