嵌套数组和ConvertTo-Json [英] Nested arrays and ConvertTo-Json
问题描述
要使用REST API,我必须传递一个如下所示的JSON对象:
To use a REST API, I must pass a JSON object that looks like this:
{ "series" :
[{
"metric": "custom.powershell.gauge",
"points":[[1434684739, 1000]]
}
]
}
请注意此处的嵌套数组.我无法重现这一点.这是我的代码:
Note the nested array here. I cannot get to reproduce this. Here is my code:
[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"}]}
我尝试了很多事情,我无法嵌套两个数组,它总是看起来像一个数组.
I've tried many things, I cannot get the 2 arrays to be nested, it always end up looking like a single array.
在同一张纸上,有人请对此进行解释:
On the same note, came someone explain this please:
> $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
来自哪里?
感谢您的帮助.
推荐答案
解释是(1,2),(3,4
)是一个数组数组,但是Powershell用管道|
分割了第一级,您没有给出这些阵列的名称,以便串行器提供.首先尝试一下:
The explanation is that (1,2),(3,4
) is an array of array, but Powershell split the first level with the pipe |
, and you don't give a name for these arrays so the serializer supplies it. First have a try to this :
# 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
对我来说,它可以满足您的需求:
For me it gives something close to what you need:
{
"series": [
{
"points": [
[
1,
2
],
[
3,
4
]
],
"metric": "custom.powershell.gauge"
}
]
}
这篇关于嵌套数组和ConvertTo-Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!