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

ConvertTo-Json忽略内部对象数组问题排查

PowerShell嵌套对象转JSON丢失数组的问题解决

问题原因

你用@{}创建的是哈希表([hashtable]),当通过Add-Member给哈希表添加NoteProperty时,实际是给哈希表的PS包装对象(PSObject)添加属性,而非修改哈希表本身的键值对。ConvertTo-Json处理哈希表时,只会序列化其内部的键值对,不会识别PSObject上额外添加的属性,因此转换整个对象时nested_obj显示为空。而单独转换nested_obj时,PowerShell会自动将哈希表包装为PSObject,此时能识别到添加的属性,所以输出正常。

解决方案

方案1:直接操作哈希表的键值对(推荐)

不需要用Add-Member,直接通过哈希表的键值对语法添加嵌套内容:

$settings = @{}

# 直接创建嵌套哈希表并设置数组属性
$settings['nested_obj'] = @{
    nested_property = @("1", "2")
}

# 输出结果:{"nested_obj":{"nested_property":["1","2"]}}
Write-Host ($settings | ConvertTo-Json -Compress -Depth 100)

方案2:使用PSCustomObject替代哈希表

如果需要用Add-Member动态扩展对象,初始就用PSCustomObject而非哈希表:

# 初始对象用PSCustomObject
$settings = [PSCustomObject]@{}

# 添加嵌套的PSCustomObject
$settings | Add-Member -Type NoteProperty -Name nested_obj -Value [PSCustomObject]@{}

# 给嵌套对象添加数组属性
$settings.nested_obj | Add-Member -Type NoteProperty -Name nested_property -Value @("1", "2")

# 输出结果:{"nested_obj":{"nested_property":["1","2"]}}
Write-Host ($settings | ConvertTo-Json -Compress -Depth 100)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:04:58