Skip to content

Commit eaca1bb

Browse files
authored
Merge pull request #40 from Readify/encoding
Escape non-ascii characters in json payloads.
2 parents 513a294 + 8ceaf79 commit eaca1bb

File tree

4 files changed

+2126
-5
lines changed

4 files changed

+2126
-5
lines changed

functions/Invoke-Method.ps1

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,11 @@ function Invoke-Method {
164164

165165
if ($PSBoundParameters.ContainsKey('Body')) {
166166
if ($ContentType -eq 'application/json') {
167-
$params.Body = $Body | ConvertTo-Json -Compress
167+
if ($PSVersionTable.PSVersion -ge '6.2.0') {
168+
$params.Body = $Body | ConvertTo-Json -Compress -EscapeHandling EscapeNonAscii
169+
} else {
170+
$params.Body = $Body | ConvertTo-Json -Compress | ConvertTo-UnicodeEscape
171+
}
168172
} else {
169173
$params.Body = $Body
170174
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
function ConvertTo-UnicodeEscape {
2+
<#
3+
.SYNOPSIS
4+
Escapes non-ascii characters in a given string
5+
.DESCRIPTION
6+
Escapes non-ascii characters in a given string
7+
.EXAMPLE
8+
PS C:\> 'A Náme' | ConvertTo-UnicodeEscape
9+
10+
Escapes the `á` to json compliant `\u00E1`
11+
.EXAMPLE
12+
PS C:\> $data | ConvertTo-Json -Compress | ConvertTo-UnicodeEscape
13+
14+
Converts `$data` to json and escapes any non ascii characters
15+
#>
16+
[CmdletBinding()]
17+
Param (
18+
# String to escape
19+
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
20+
[String]
21+
$InputObject
22+
)
23+
24+
$output = ''
25+
26+
foreach ($char in $InputObject.GetEnumerator()) {
27+
$i = [int]$char
28+
29+
if ($i -lt 128) {
30+
Write-Debug -Message "$char ($i) does not need escaping."
31+
$output += $char
32+
} else {
33+
Write-Debug -Message "$char ($i) needs escaping."
34+
35+
$hex = '{0:X}' -f $i
36+
Write-Debug -Message "Character as hex: $hex"
37+
38+
$escape = '\u' + $hex.PadLeft(4, '0')
39+
Write-Debug -Message "Full escape sequence: $escape"
40+
41+
$output += $escape
42+
}
43+
}
44+
45+
$output
46+
}

0 commit comments

Comments
 (0)