微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

嵌套数组和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"
                   }
               ]
}

原文地址:https://www.jb51.cc/js/155206.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐