powershell - Nested arrays and ConvertTo-Json -
to use rest api, must pass json object looks this:
{ "series" : [{ "metric": "custom.powershell.gauge", "points":[[1434684739, 1000]] } ] }
note nested array here. cannot reproduce this. here 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
and here output:
{"series":[{"points":[1434685292,95],"metric":"custom.powershell.gauge"}]}
i've tried many things, cannot 2 arrays nested, end looking single array.
on same note, came explain 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 } ]
where these value
, count
coming from?
thanks help.
the explanation (1,2),(3,4
) array of array, powershell split first level pipe |
, , don't give name these arrays serializer supplies it. first have try :
# first build array of array $z = (1,2),(3,4) # convert json using , ,$z | convertto-json -depth 5 -compress [psobject]@{"points"=$z} | convertto-json -depth 5 -compress
it gives first step:
{"value":[[1,2],[3,4]],"count":2} {"points":[[1,2],[3,4]]}
now solution propose :
# first build array of array $z = (1,2),(3,4) # build pscustom object $a = [pscustomobject]@{"series" = ,@{"metric"="custom.powershell.gauge"; "points"=$z}} # @ end convert json # don't forget **depth** parameter (use **compress** retreive 1 line above) $a | convertto-json -depth 5
for me gives close need:
{ "series": [ { "points": [ [ 1, 2 ], [ 3, 4 ] ], "metric": "custom.powershell.gauge" } ] }
Comments
Post a Comment