要使用REST API,我必须传递一个如下所示的JSON对象:
{ "series" :
[{
"metric": "custom.powershell.gauge",
"points":[[1434684739, 1000]]
}
]
}
Run Code Online (Sandbox Code Playgroud)
请注意这里的嵌套数组.我无法重现这一点.这是我的代码:
[int][double]$unixtime=get-date ( (get-date).ToUniversalTime() ) -UFormat %s
$obj=@{}
$series=@{}
$array=@()
$points=@()
$value=get-random -Minimum 0 -Maximum 100
$series.add("metric","custom.powershell.gauge")
$points=@(@($unixtime, $value))
$series.add("points",$points)
$obj.Add("series",@($series))
$json=$obj | ConvertTo-Json -Depth 30 -Compress
$json
Run Code Online (Sandbox Code Playgroud)
这是输出:
{"series":[{"points":[1434685292,95],"metric":"custom.powershell.gauge"}]}
Run Code Online (Sandbox Code Playgroud)
我尝试了很多东西,我不能让2个数组嵌套,它总是看起来像一个数组.
在同一张纸条上,请有人解释一下:
> $a=(1,2)
> $a
1
2
> $a | ConvertTo-Json
[
1,
2
]
> $b=($a,$a)
> $b
1
2
1
2
> $b | ConvertTo-Json
[
{
"value": [
1,
2
],
"Count": 2
},
{
"value": [
1,
2
],
"Count": 2
}
]
Run Code Online (Sandbox Code Playgroud)
在哪里这些value和Count来自何处?
谢谢你的帮助.
JPB*_*anc 12
解释是(1,2),(3,4:)是一个数组数组,但是Powershell将第一个级别与管道分开|,并且您没有为这些数组命名,因此序列化程序提供它.首先尝试这个:
# First build your array of array
$z = (1,2),(3,4)
# convert it to JSON using the ,
,$z | ConvertTo-Json -Depth 5 -Compress
[psobject]@{"points"=$z} | ConvertTo-Json -Depth 5 -Compress
Run Code Online (Sandbox Code Playgroud)
它给出了第一步:
{"value":[[1,2],[3,4]],"Count":2}
{"points":[[1,2],[3,4]]}
Run Code Online (Sandbox Code Playgroud)
现在我建议的解决方案:
# First build your array of array
$z = (1,2),(3,4)
# Then build a PSCustom object
$a = [pscustomobject]@{"series" = ,@{"metric"="custom.powershell.gauge"; "points"=$z}}
# At the end convert it to JSON
# don't forget the **Depth** parameter (use **Compress** to retreive one line like above)
$a | ConvertTo-Json -Depth 5
Run Code Online (Sandbox Code Playgroud)
对我来说,它提供了接近你需要的东西:
{
"series": [
{
"points": [
[
1,
2
],
[
3,
4
]
],
"metric": "custom.powershell.gauge"
}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10441 次 |
| 最近记录: |