Powershell create array of arrays

前端 未结 3 1750
失恋的感觉
失恋的感觉 2021-01-16 07:09

I\'m trying to push data to a REST api using powershell.

http://influxdb.com/docs/v0.8/api/reading_and_writing_data.html

The server expects data like so:

3条回答
  •  滥情空心
    2021-01-16 07:30

    To complement Etan Reisner's helpful answer (whose of use unary , to create a nested array solves the problem):

    PowerShell's hashtable literals are quite flexible with respect to incorporating variable references, expression, and commands, which makes for a more readable solution:

    ,, [ordered] @{
        name = 'hd_used'
        columns = 'value', 'host', 'mount'
        points = , (23.2, 'serverA', 'mnt')
    } | ConvertTo-Json -Depth 3
    

    This yields:

    [
      {
        "name": "hd_used",
        "columns": [
          "value",
          "host",
          "mount"
        ],
        "points": [
          [
            23.2,
            "serverA",
            "mnt"
          ]
        ]
      }
    ]
    

    Note how the array-construction operator (,) is applied twice at the beginning of the pipeline (before [ordered]):

    • first to turn the ordered hashtable into a (single-item) array,
    • and the 2nd time to wrap that array in an outer array.

    Sending the result through the pipeline makes PowerShell unwrap any collection, i.e., enumerate the collection items and send them one by one, which in this case strips away the outer array, leaving ConvertTo-Json to process the inner array, as desired.
    Note that passing an array adds a level to the hierarchy, which is why the -Depth value was increased to 3 above.

    • Caveat: Any property whose hierarchy level is deeper than -Depth is stringified (evaluated as if placed inside "$(...)"), which in the case of an array would simply join the array elements with a space; e.g., array 23.2, 'serverA', 'mnt' would turn to a single string with literal contents 23.2 serverA mnt.

    Note how the arrays above do not use syntax @(...), because it is generally not necessary to construct arrays and is actually less efficient: simply ,-enumerate the elements, and, if necessary, enclose in (...) for precedence (although @() is syntactically convenient for creating an empty array).

    + with an array as the LHS doesn't so much unwrap (unroll) its RHS, but concatenates arrays, or, to put it differently, allows you to append multiple individual items; e.g.:

    $a = 1, 2
    $a += 3, 4  # add elements 3 and 4 to array 1, 2 to form array 1, 2, 3, 4
    

    Note that the use of += actually creates a new array behind the scenes, given that arrays aren't resizable.

提交回复
热议问题