Lost Single Item Array in Powershell Array to JSON Conversion

I thought I would throw this out there for anyone possibly running into this issue. Basically, when converting a PSObject to JSON in Powershell, I had an array that only had one value in some cases. When this happened the conversion would unpack the array and I would get the @{} at the root level of the property instead of an array:


Obviously, this can be a major issue if you are sending the JSON to something expecting an array there. We could fix the end-point and design it to work with either, but we don’t always have access or control over the end-point. So how can we fix this at the root?

First let’s look at our code that we are using prior:


Here we are using a hashtable which is VERY easy to work with, and then converting it to an object. This allows us to keep the ordering of objects on conversion and actually makes the object easier to work with later in the code. You can’t tell from the image but those functions return an array to the hashtable property.

From here we’d do a simple pipeline from the $graphs variable into the ConvertTo-JSON cmdlet, but this gave us the code you see in the first image. Destroying our ROWS array. That will not do!

The solution to this is to build the object manually from scratch and define the property we want to be an array, as a ListArray type explicitly. Then add our value to that. This has some additional functionality we don’t care about, but solves our problem as well.

The code for our solution looks like this:


We define our value for our arrays as System.Collection.ArrayList and set the new property value to that. This locks our array into the object. We then use it as we would a normal powershell array and add our arrays or objects to it. Then when we convert it to JSON we get this:


Problem solved. I hope this can help someone else out as well!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s