Home > Enterprise >  Azure Functions: Powershell Push-OutputBinding format JSON
Azure Functions: Powershell Push-OutputBinding format JSON

Time:03-15

I have used below code in my azure PowerShell HTTP function. On triggering this function, I receive JSON body but not as in the same order I have provided in code. Please let me know how can I receive JSON body in response as in same order I have coded i.e. {"Status": "val", "Msg": "val", "Value": "val"}

Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 
    StatusCode = [HttpStatusCode]::OK
    Headers = @{
        "Content-type" = "application/json"
    }
    Body = @{
        "Status" = $status
        "Msg" = $body
        "Value" = $val   
    } | ConvertTo-Json
})

CodePudding user response:

The order of keys in a hash table is not determined.

Use an ordered dictionary instead of a hashtable. This will preserve the order of your keys as you intended them.

To do so, simply add the [Ordered] type in front of your body hashtable.

Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 
    StatusCode = [HttpStatusCode]::OK
    Headers = @{
        "Content-type" = "application/json"
    }
    # Will keep the order of the keys as specified.
    Body = [Ordered]@{
        "Status" = $status
        "Msg" = $body
        "Value" = $val   
    } | ConvertTo-Json
})

Beginning in PowerShell 3.0, you can use the [ordered] attribute to create an ordered dictionary (System.Collections.Specialized.OrderedDictionary) in PowerShell.

Ordered dictionaries differ from hash tables in that the keys always appear in the order in which you list them. The order of keys in a hash table is not determined.

Source

  • Related