要使用REST API,我必须传递一个如下所示的JSON对象:
{ "series" :
[{
"metric": "custom.powershell.gauge",
"points":[[1434684739, 1000]]
}
]
}注意这里的嵌套数组。我不能重现这个。下面是我的代码:
[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下面是输出:
{"series":[{"points":[1434685292,95],"metric":"custom.powershell.gauge"}]}我尝试了很多方法,我不能将两个数组嵌套在一起,它总是看起来像一个单独的数组。
同样的,有人来解释一下这个:
> $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
}
]这些value和Count是从哪里来的?
谢谢你的帮助。
发布于 2015-06-19 13:13:39
解释是,(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它提供了第一步:
{"value":[[1,2],[3,4]],"Count":2}
{"points":[[1,2],[3,4]]}现在我提出的解决方案是:
# 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对我来说,它提供了一些你需要的东西:
{
"series": [
{
"points": [
[
1,
2
],
[
3,
4
]
],
"metric": "custom.powershell.gauge"
}
]
}发布于 2016-09-13 00:31:23
晚了,但我想提出一个更直观,易于扩展的解决方案(我和其他人一样,也是一个视觉学习者,所以像下面这样的代码块可以帮助我更容易地理解东西):
[int][double]$unixtime = Get-Date ((Get-Date).ToUniversalTime()) -UFormat %s
$value = Get-Random -Minimum 0 -Maximum 100
$body = @{
'series' = @(
[Ordered]@{
'metric'='custom.powershell.gauge'
'points' = @(
,@($unixtime,$value)
)
}
)
}
ConvertTo-Json -InputObject $body -Depth 4输出:
{
"series": [
{
"metric": "custom.powershell.gauge",
"points": [
[
1473698742,
96
]
]
}
]
}-Depth 4为您的点值加上一组额外的方括号,[Ordered]确保哈希表按照最初指定的顺序排序。在发送之前不要忘记-Compress,就像其他人所说的那样。
发布于 2015-06-20 22:33:20
正如JPBlanc建议的那样,创建自定义对象是可行的。下面是我的代码:
[long]$value=Get-Random -Minimum 0 -Maximum 100
$points=,@($unixtime, $value)
$metricname="custom.powershell.gauge"
$obj = [pscustomobject]@{"series" = ,@{"metric" = $metricname; "points"=$points}}
$json=$obj | ConvertTo-Json -Depth 5 -Compress以下哪项输出:
{"series":[{"points":[[1434810163,53]],"metric":"custom.powershell.gauge"}]}别忘了指定一个大于2的深度。
谢谢!
https://stackoverflow.com/questions/30929633
复制相似问题