You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中向JSON对象添加数组时空ArrayList被转为空字符串的问题排查与解决

为什么PowerShell中ArrayList转JSON时会变成空字符串而不是数组?

我来帮你分析这个问题,并且给出对应的解决办法:

问题原因

PowerShell的ConvertTo-Json cmdlet在处理空的System.Collections.ArrayList对象时,默认会把它序列化为空字符串,而非JSON数组。这是因为它对非泛型集合的处理逻辑和泛型集合有差异:空的非泛型ArrayList会被判定为“空值”而非空集合,所以序列化后就变成了""。

解决办法

这里有几个实用的方案可以解决这个问题:

方案1:使用泛型列表List<T>替代ArrayList

泛型集合在ConvertTo-Json中会被正确识别为数组,哪怕是空集合也会序列化为[]。修改你的脚本如下:

$json = @{ 
    "A"="Hello world"; 
    "B"= New-Object System.Collections.Generic.List[object]; 
}
$json2 = @{ 
    'C'="Foo Bar"; 
    'D'=New-Object System.Collections.Generic.List[object]; 
}
$json.B.Add($json2) # 推荐用Add方法而非+=,更符合集合操作的规范
$json | ConvertTo-Json -Depth 3 | Out-File "test.json"

注意:这里加上-Depth 3是因为默认序列化深度为2,你的嵌套结构需要更高的深度才能完整序列化所有层级。

方案2:手动将空ArrayList转换为数组

如果你坚持要使用ArrayList,可以在序列化前把空的ArrayList转为PowerShell原生数组:

$json = @{ 
    "A"="Hello world"; 
    "B"= New-Object System.Collections.ArrayList; 
}
$json2 = @{ 
    'C'="Foo Bar"; 
    'D'=New-Object System.Collections.ArrayList; 
}
# 将空ArrayList转换为数组
$json2.D = $json2.D.ToArray()
$json.B.Add($json2)
$json | ConvertTo-Json -Depth 3 | Out-File "test.json"

方案3:直接使用PowerShell原生数组

如果不需要动态添加元素的功能,直接用PowerShell原生数组(@())会更简单,它会被ConvertTo-Json正确序列化为数组:

$json = @{ 
    "A"="Hello world"; 
    "B"= @(); 
}
$json2 = @{ 
    'C'="Foo Bar"; 
    'D'= @(); 
}
$json.B += $json2
$json | ConvertTo-Json -Depth 3 | Out-File "test.json"

运行以上任意一种方案,你都会得到期望的JSON结果:

{
  "A": "Hello world",
  "B": [
    {
      "C": "Foo Bar",
      "D": []
    }
  ]
}

内容的提问来源于stack exchange,提问作者user16527495

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:02:32