Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

ConvertFrom-Json with empty JSON returns an empty list

Context:

  • You want to receive an JSON and check whether the JSON is empty or not.

Problem:

You cannot check empty JSON with -eq operator, and -eq doesn’t return true/false.

> $hoge = (Get-Content ./empty.json | ConvertFrom-Json)
> $hoge -eq ""
> $hoge -eq $null
> $hoge -eq $false

Reason:

ConvertFrom-Json returns empty list when the JSON is empty. In above examples (the left operand is a list), -eq operator behaves as a filter, not a conditional operator.

Solution

If you want to check whether the JSON is empty or not, there is more than one way to do it.

  • Just put the result of ConvertFrom-Json into if condition. Empty lists are falsy in PowerShell.
> $hoge = (Get-Content ./empty.json | ConvertFrom-Json)                           
> if ($hoge) { "Not Empty" } else { "Empty" }          
  • Use Length property of result of ConvertFrom-Json (Empty list will return 0). Note that you should use @() with result of ConvertFrom-Json because a list with only one element behaves as scalar object (this is another gocha of PowerShell …).