嵌套数组和ConvertTo-Json

要使用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"}]}

我尝试了很多东西,我不能让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,"Count":  2
    }
]

这些价值和伯爵来自哪里?

谢谢你的帮助.

解决方法

解释是(1,2),(3,4)是一个数组的数组,但是Powershell用管道分割了第一级,你没有给这些数组命名,所以序列化器提供它.首先尝试这个:
# First build your array of array
$z = (1,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,4]]}

现在我建议的解决方案:

# First build your array of array
$z = (1,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"
                   }
               ]
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...