0

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.

2
  • 2
    The JSON sample is invalid. Please edit the question and add parsable, valid data. Commented Dec 14, 2018 at 7:31
  • Sorry, Its valid json now Commented Dec 14, 2018 at 7:36

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's it! Nice and thanks alot. Is there any good documentation you can recommend for digging deeper into powershell? I'm very new to it
"Windows PowerShell in Action" book, use Get-Help like ` Get-Help Get-Process -Examples` and search this site for lots of good examples and answers. Use ISE or VSCode to write and debug code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.