Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConvertTo-JSON an array with a single item

I'm trying to create a JSON-serialized array. When that array contains only one item I get a string, not an array of strings (in JSON).

Multiple Items (works as expected):

PS C:\> @("one", "two") | ConvertTo-JSON [     "one",     "two" ] 

Single Item Array (not as expected):

PS C:\> @("one") | ConvertTo-JSON "one" 

Am I missing something?

like image 502
Luggage Avatar asked Sep 06 '13 17:09

Luggage


People also ask

How do I add an item to an array in PowerShell?

You can use the += operator to add an element to an array. The following example shows how to add an element to the $a array. When you use the += operator, PowerShell actually creates a new array with the values of the original array and the added value.

What does ConvertFrom Json do?

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom PSCustomObject object that has a property for each field in the JSON string. JSON is commonly used by web sites to provide a textual representation of objects.

How do I parse Json data in PowerShell?

PowerShell makes it easy to modify JSON by converting JSON to a PSCustomObject. The object can then be modified easily like any other object. The object can then be exported back out using ConvertTo-Json. Now if we're on a computer without PowerShell 7.1 we try to run the same command in PowerShell 5.1 but it fails!

How do I convert text to Json in PowerShell?

-InputObjectSpecifies the objects to convert to JSON format. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe an object to ConvertTo-Json . The InputObject parameter is required, but its value can be null ( $null ) or an empty string.


2 Answers

Try without the pipeline:

PS C:\> ConvertTo-Json @('one', 'two') [     "one",     "two" ] PS C:\> ConvertTo-Json @('one') [     "one" ]
like image 118
Ansgar Wiechers Avatar answered Oct 09 '22 10:10

Ansgar Wiechers


I hit this problem as well but it was because my structure was too deep and ConvertTo-Json flattens everything below a certain depth to a string.

For example:

PS C:\> $MyObject = @{ "a" = @{ "b" = @{ "c" = @("d") } } } PS C:\> ConvertTo-Json $MyObject {     "a":  {               "b":  {                         "c":  "d"                     }           } } 

To fix this, you can pass a larger value to -Depth

PS C:\> ConvertTo-Json $MyObject -Depth 100 {     "a":  {               "b":  {                         "c":  [                                   "d"                               ]                     }           } } 
like image 44
nkron Avatar answered Oct 09 '22 12:10

nkron