-
Notifications
You must be signed in to change notification settings - Fork 7.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ConvertTo-Json for empty array produces null #23837
Comments
I do realize this is because the pipeline has no items to send to the cmdlet, so the begin and end happen and no output, I would expect that the -AsArray with no items would be an empty json array |
If others want a workaround, use |
Indeed, Write-Output -NoEnumerate @() | ConvertTo-Json
# More succinct, but obscure shortcut:
, @() | ConvertTo-Json Note:
|
$Array | ConvertTo-Json will also flatten a single-item array so, in my experience, you are always better off using the -InputObject parameter
|
Good point, @roe-dk; since
# Ensures that a JSON *array* is created even if only ONE file matches.
# Two or more input objects of necessity always result in a JSON array.
Get-ChildItem *.txt | Select-Object Name | ConvertTo-Json -AsArray However, as in the case at hand, there will be NO output if no files matching By contrast, if you use # -> '[]'
ConvertTo-Json @(Get-ChildItem nosuch* | Select-Object Name ) Using just # -> 'null'
ConvertTo-Json (Get-ChildItem nosuch* | Select-Object Name ) The technical reason is that Due to the behavior discussed in #10952, |
If we explicitly state we want it as an array using |
The problem is that that there is no "it" in your scenario: |
Then again, your point is defensible too: wrap the to-be-JSON-converted input in an array, and if there's no input, wrap "nothing" in an array, i.e. output an empty array. On further reflection I personally agree that this behavior would be more helpful, I guess we'll have to wait for what the relevant WG has to say. |
I understand and knew it's be a breaking behavior going in. Hoping for a 7.5 or 7.6 change 😍 |
Prerequisites
Steps to reproduce
$null -eq (@() | ConvertTo-Json -AsArray)
is$true
but should be false because an empty array in json is[]
Expected behavior
Actual behavior
PS> @() | ConvertTo-Json -AsArray
Error details
N/A
Environment data
Visuals
No response
The text was updated successfully, but these errors were encountered: