PowerShell中如何将数组正确转换为符合API要求的JSON格式
问题核心是你在定义哈希表$RESTdata时,没有把scopes、sources、actions明确声明为数组类型,导致转换JSON时被解析成对象。调整-Depth参数没用,因为这个参数只控制嵌套对象的解析层级,不改变数据类型。
错误示例(会生成对象)
如果你的哈希表是这样定义的:
$RESTdata = @{ name = "TestTask" scopes = @{ scope1 = "read" } # 哈希表结构,转JSON会变成{} sources = @{ source1 = "db" } actions = @{ action1 = "execute" } } $RESTdata | ConvertTo-Json
输出的JSON里,scopes等字段会是对象:
{
"name": "TestTask",
"scopes": {
"scope1": "read"
},
"sources": {
"source1": "db"
},
"actions": {
"action1": "execute"
}
}
正确定义方式(生成数组)
把需要数组的字段用@()包裹,声明为数组类型。根据API需求,数组里可以放单个值、多个值,或者嵌套的哈希表数组:
情况1:数组内是单个值
$RESTdata = @{ name = "TestTask" scopes = @("read") # 用@()定义数组 sources = @("db") actions = @("execute") } $RESTdata | ConvertTo-Json
输出符合要求的数组格式:
{
"name": "TestTask",
"scopes": [
"read"
],
"sources": [
"db"
],
"actions": [
"execute"
]
}
情况2:数组内是多个对象
如果API需要数组里包含多个键值对对象,这样定义:
$RESTdata = @{ name = "TestTask" scopes = @( @{ scope = "read"; resource = "user" }, @{ scope = "write"; resource = "post" } ) sources = @( @{ type = "db"; name = "mysql" }, @{ type = "api"; url = "https://example.com" } ) actions = @( @{ name = "execute"; param = "id=1" }, @{ name = "log"; level = "info" } ) } $RESTdata | ConvertTo-Json -Depth 3 # 嵌套层级较深时需调整Depth
输出的JSON中,scopes等字段会是包含多个对象的数组:
{
"name": "TestTask",
"scopes": [
{
"scope": "read",
"resource": "user"
},
{
"scope": "write",
"resource": "post"
}
],
"sources": [
{
"type": "db",
"name": "mysql"
},
{
"type": "api",
"url": "https://example.com"
}
],
"actions": [
{
"name": "execute",
"param": "id=1"
},
{
"name": "log",
"level": "info"
}
]
}
关键总结
- 要生成JSON数组,PowerShell中必须用
@()把对应字段定义为数组类型,而不是哈希表(@{})。 -Depth参数仅当数组/哈希表有多层嵌套时需要调整,用来确保深层结构被完整解析,和字段是否为数组无关。
内容的提问来源于stack exchange,提问作者cambis

