Home > Back-end >  Converting 2D JSON array that is structured like CSV to array of objects
Converting 2D JSON array that is structured like CSV to array of objects

Time:08-28

I'm getting through a webservice a string as a response. The string has the following two-dimensional-array structure with a header.

[
["name", "age","gender"],
["John doe","34","male"],
["Jane doe","23","Female"],
["Bob Doe","35","Male"]
]

I have to loop through all of those elements and I guess I could split my way out of it and create an array.

But is there an more elegant way to convert that string into a two-dimensional structure in powershell?

Thanks in advance!

CodePudding user response:

Here is a possible solution that converts each row into a PSCustomObject (similar to what you'd get from ConvertFrom-CSV).

# Test input
$response = @'
[
["name", "age","gender"],
["John doe","34","male"],
["Jane doe","23","Female"],
["Bob Doe","35","Male"]
]
'@

# Convert input string to a 2D array
$temp = $response | ConvertFrom-Json

# Interpret the 2D array like a CSV (first row defines the property names)

$header, $dataRows = $temp   # Split the temp array into header and data rows

$data = foreach( $row in $dataRows ) {

    # Create an ordered hashtable
    $ht = [ordered]@{}

    # Loop over the columns of the current row
    for( $i = 0; $i -lt $row.Count;   $i ){
       # Assign current column to the hashtable, using a key from the 1st row
       $ht[ $header[$i] ] = $row[$i]
    }

    # Convert the hashtable to a PSCustomObject and (implicitly) output it
    [PSCustomObject] $ht
}

# Output array of PSCustomObject
$data

Output:

name     age gender
----     --- ------
John doe 34  male
Jane doe 23  Female
Bob Doe  35  Male

To get individual values:

$data[0].name # Outputs "John doe"
$data[1].age  # Outputs "23"
  • Related