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?
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.
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.
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!
-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.
Try without the pipeline:
PS C:\> ConvertTo-Json @('one', 'two') [ "one", "two" ] PS C:\> ConvertTo-Json @('one') [ "one" ]
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" ] } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With