Skip to content

Commit

Permalink
Escape non-ascii characters in json payloads.
Browse files Browse the repository at this point in the history
Even if the content type indicates a valid unicode charset, Zendesk does like non-ascii characters that aren't escaped.

PS 6.2 added the `-EscapeHanding` parameter to `ConvertTo-Json` which can be used.
  • Loading branch information
RobFaie committed Mar 29, 2020
1 parent 89aedb9 commit 4d727c3
Show file tree
Hide file tree
Showing 4 changed files with 2,029 additions and 4 deletions.
6 changes: 5 additions & 1 deletion functions/Invoke-Method.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,11 @@ function Invoke-Method {

if ($PSBoundParameters.ContainsKey('Body')) {
if ($ContentType -eq 'application/json') {
$params.Body = $Body | ConvertTo-Json -Compress
if ($PSVersionTable.PSVersion -ge '6.2.0') {
$params.Body = $Body | ConvertTo-Json -Compress -EscapeHandling EscapeNonAscii
} else {
$params.Body = $Body | ConvertTo-Json -Compress | ConvertTo-UnicodeEscape
}
} else {
$params.Body = $Body
}
Expand Down
46 changes: 46 additions & 0 deletions internal/ConvertTo-UnicodeEscape.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
function ConvertTo-UnicodeEscape {
<#
.SYNOPSIS
Escapes non-ascii characters in a given string
.DESCRIPTION
Escapes non-ascii characters in a given string
.EXAMPLE
PS C:\> 'A Náme' | ConvertTo-UnicodeEscape
Escapes the `á` to json compliant `\u00E1`
.EXAMPLE
PS C:\> $data | ConvertTo-Json -Compress | ConvertTo-UnicodeEscape
Converts `$data` to json and escapes any non ascii characters
#>
[CmdletBinding()]
Param (
# String to escape
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[String]
$InputObject
)

$output = ''

foreach ($char in $InputObject.GetEnumerator()) {
$i = [int]$char

if ($i -lt 128) {
Write-Debug -Message "$char ($i) does not need escaping."
$output += $char
} else {
Write-Debug -Message "$char ($i) needs escaping."

$hex = '{0:X}' -f $i
Write-Debug -Message "Character as hex: $hex"

$escape = '\u' + $hex.PadLeft(4, '0')
Write-Debug -Message "Full escape sequence: $escape"

$output += $escape
}
}

$output
}
Loading

0 comments on commit 4d727c3

Please sign in to comment.