简体   繁体   English

如何用 PowerShell 创建一个有效的空 JSON 数组?

[英]How to create a valid empty JSON array with PowerShell?

Converting arrays to JSON string in PowerShell couldn't be more simple:将 arrays 转换为 PowerShell 中的 JSON 字符串再简单不过了:

@(1,2,3) | ConvertTo-Json

Produces:产生:

[
    1,
    2,
    3
]

However if the array is empty the result is an empty string:但是,如果数组为空,则结果为空字符串:

@() | ConvertTo-Json

Results an empty string instead of [] .结果是一个空字符串而不是[]

It works without pipelining 它没有流水线工作

PS C:\> ConvertTo-Json @()
[

]

This is a use case for the unary comma operator, https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.2这是一元逗号运算符的用例, https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.2

The pipeline is breaking the array apart.管道将阵列分开。 In the first example, the array is broken apart into its integer values as it passes through the pipeline (I'm not sure of what the actual mechanics of it being reassembled on the other side are: if it's the pipeline acting logically seeing three integers grouped together or if it's some interpretation being done by the receiving cmdlet itself).在第一个示例中,数组在通过管道时被分解为 integer 个值(我不确定它在另一侧重新组装的实际机制是什么:如果管道在逻辑上看到三个整数组合在一起,或者如果它是由接收 cmdlet 本身完成的一些解释)。 Regardless, using the unary operator ',' creates an array of one element.无论如何,使用一元运算符 ',' 创建一个只有一个元素的数组。 When used as either , @(1, 2, 3) or , @() it creates a container array which is broken apart by the pipeline still, but the sub-arrays are the objects being passed through and preserved as intended to be interpreted by the ConvertTo-Json cmdlet properly.当用作, @(1, 2, 3), @()时,它会创建一个容器数组,该数组仍然被管道分开,但子数组是被传递并保留的对象,以供解释通过 ConvertTo-Json cmdlet 正确。 Assuming your array is stored in a variable like $myArray, the following general code will work for all situations:假设您的数组存储在 $myArray 之类的变量中,以下通用代码适用于所有情况:

, $myArray | ConvertTo-Json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM