goldenone
goldenone

Reputation: 11

JSON Array - Powershell

I need an JSON array string like the following: [{"a":"1","b":"2","c“:"3","d": "4"}]

If I am using the following code, I am getting {medik:[{"a":"1","b":"2","c“:"3","d": "4"}]}

$body = @{
   medik =  @(
        @{
            a = '1'
            b = '2'
            c = '3'
            d = '4'
        }
    )
}
$jsbody=$body|ConvertTo-Json -Compress;
$jsbody 

Can anyone help me? Thanks in advance!

Upvotes: 0

Views: 49

Answers (1)

ekeeling
ekeeling

Reputation: 381

Try it without using the pipeline.

When using the pipeline you are passing the array one hashtable at a time to ConvertTo-Json. Since there is only one hashtable, it is seen as a single hashtable not an array of hashtables.

ConvertTo-Json @(@{a = '1'; b = '2'; c = '3'; d = '4'})

Output:

PS C:\tmp\overflow> $body = @(@{a = '1'; b = '2'; c = '3'; d = '4'})
>> ConvertTo-Json $body

[
  {
    "d": "4",
    "c": "3",
    "b": "2",
    "a": "1"
  }
]

Upvotes: 1

Related Questions