PowerShell构建含嵌套列表的JSON时遇到问题求助
PowerShell组装嵌套JSON结构的解决方案
问题描述
需要生成包含totalCount字段及嵌套list数组的JSON结构,数组内对象需带有parameters子对象(包含relayIds、lightIds等数组类型字段),使用for循环填充值时无法生成正确的嵌套列表结构。
目标JSON结构
{ "totalCount": 1, "list": [ { "type": "ToggleLightingState", "order": 1, "delay": null, "postDelay": null, "name": "Toggle lighting state of light L-17E-611-KB-1", "parameters": { "relayIds": [], "curveType": null, "behavior": null, "duration": null, "useAssignedSpace": false, "spaceIds": [], "lightIds": [ 2408 ], "spaceGroupIds": [] } } ] }
尝试的错误代码
$ActionList = @{ @( @{ type = 'ToggleLightingState' order = 1 delay = 'null' postDelay = 'null' name = $actionSets[$i][0] } ) } ConvertTo-Json -InputObject $ActionList
错误分析
- 哈希表结构错误:未定义
totalCount和list键,直接在哈希表中放置数组,不符合目标JSON的顶层结构 - 空值处理错误:使用字符串
'null'而非PowerShell的$null,会导致JSON中生成字符串"null"而非原生null - 缺少
parameters子对象:未构建目标JSON中要求的嵌套参数结构 - 数组定义不完整:未包含
lightIds等需要填充的数组字段
正确实现代码
单条数据示例
# 构建单个list项的parameters子对象 $parameters = @{ relayIds = @() curveType = $null behavior = $null duration = $null useAssignedSpace = $false spaceIds = @() lightIds = @(2408) # 根据实际需求填充值 spaceGroupIds = @() } # 构建单个list项 $listItem = @{ type = 'ToggleLightingState' order = 1 delay = $null postDelay = $null name = "Toggle lighting state of light L-17E-611-KB-1" # 替换为$actionSets[$i][0] parameters = $parameters } # 构建顶层JSON结构 $ActionList = @{ totalCount = 1 # 根据实际数据数量设置 list = @($listItem) } # 转换为JSON,注意指定Depth参数(默认深度2,嵌套结构需要更大值) ConvertTo-Json -InputObject $ActionList -Depth 3
循环批量填充示例
$actionSets = @( # 模拟循环数据源 @("Toggle lighting state of light L-17E-611-KB-1", 2408) @("Toggle lighting state of light L-17E-611-KB-2", 2409) ) $listItems = @() foreach ($set in $actionSets) { $parameters = @{ relayIds = @() curveType = $null behavior = $null duration = $null useAssignedSpace = $false spaceIds = @() lightIds = @($set[1]) spaceGroupIds = @() } $listItem = @{ type = 'ToggleLightingState' order = [array]::IndexOf($actionSets, $set) + 1 delay = $null postDelay = $null name = $set[0] parameters = $parameters } $listItems += $listItem } $ActionList = @{ totalCount = $listItems.Count list = $listItems } ConvertTo-Json -InputObject $ActionList -Depth 3
关键注意事项
- 哈希表键名匹配:必须严格对应目标JSON的键名(如
totalCount、list、parameters) - 空值与数组处理:用
$null表示JSON原生null,空数组用@()定义 - 布尔值类型:直接使用PowerShell的
$true/$false,转换后会对应JSON的布尔值 - ConvertTo-Json深度:嵌套层级超过2时必须指定
-Depth参数,避免结构被截断
内容的提问来源于stack exchange,提问作者Broc Christensen
相关产品推荐
相关产品推荐

