gpt4 book ai didi

json - 嵌套数组和 ConvertTo-Json

转载 作者:行者123 更新时间:2023-12-04 13:22:47 27 4
gpt4 key购买 nike

要使用 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,
2
],
"Count": 2
}
]

这些在哪里 valueCount来自(哪里?

谢谢你的帮助。

最佳答案

解释是(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"
}
]
}

关于json - 嵌套数组和 ConvertTo-Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30929633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com