jsonpowershell

PowerShell ConvertFrom-Json ignores top-level array?


I'm trying to parse a JSON array with ConvertFrom-Json but it seems PowerShell is ignoring the array if it is on the top level.

For example, this unexpectedly returns count = 1:

'[{a:1},{b:2}]' | ConvertFrom-Json | measure

But when I put the JSON array inside an object it seems to be parsed as expected. This returns count = 2

('{list:[{a:1},{b:2}]}' | ConvertFrom-Json).list | measure

If ConvertFrom-Json does not work on JSON arrays, are there any alternatives?


Solution

  • '[{a:1},{b:2}]' | ConvertFrom-Json | measure

    What you've done is measure the number of objects returned by the pipeline. The pipeline returns an array of 2 objects, not 2 objects.

    if you want the number of things in the array you could do this:

    ('[{a:1},{b:2}]' | ConvertFrom-Json).Count

    With the second example, PowerShell is unrolling list to get the items inside it (normal PowerShell pipeline behavior).