我正在尝试将数据转换为JSON作为REST API的输入。我面临的挑战是数据应包含多个深度(缺少更好的语言)。我现在使用的代码是:
(@{name = "Contoso"; all_assets = "false"; all_users="false"; rules= @{type="fqdn"; operator="match"; terms=@("contoso") } }| ConvertTo-Json)
现在的输出是:
{
"all_users": "false",
"name": "Contoso",
"all_assets": "false",
"rules": {
"operator": "match",
"terms": [
"contoso"
],
"type": "fqdn"
}
}
REST-Api抱怨数据包含无效字符。查看输出,“规则:”部分包含{}而不是[]。我一直在尝试各种技巧,但似乎无法弄清楚。
有人知道我在做什么错吗?
答案 0 :(得分:2)
如果您希望rules
包含对象数组而不是具有属性的对象,请用rules
将@()
内的所有内容括起来。
由于terms
然后成为第3级,因此需要将参数-Depth
添加到ConvertTo-Json cmdlet:
为了获得更好的可读性,我不做单行打印
@{
name = "Contoso"
all_assets = "false"
all_users = "false"
rules = @(
@{
type = "fqdn"
operator = "match"
terms = @("contoso")
}
)
} | ConvertTo-Json -Depth 3
输出:
{ "all_users": "false", "name": "Contoso", "all_assets": "false", "rules": [ { "operator": "match", "terms": [ "contoso" ], "type": "fqdn" } ] }
答案 1 :(得分:0)
为了它的价值...
不是解决Unexpected ConvertTo-Json results? Answer: it has a default -Depth of 2问题的答案,而是通常如何使用ConvertTo-Expression
cmdlet从Json
文件构建PowerShell表达式:
'{
"all_users": "false",
"name": "Contoso",
"all_assets": "false",
"rules": [
{
"operator": "match",
"terms": [
"contoso"
],
"type": "fqdn"
}
]
}' | ConvertFrom-Json | ConvertTo-Expression
[pscustomobject]@{
'all_users' = 'false'
'name' = 'Contoso'
'all_assets' = 'false'
'rules' = ,[pscustomobject]@{
'operator' = 'match'
'terms' = ,'contoso'
'type' = 'fqdn'
}
}