Changed JSON stringification to preserve UTF (#6330)

This commit is contained in:
Yuriy Glukhov
2017-09-15 11:53:58 +03:00
committed by Andreas Rumpf
parent 034e6a3468
commit 7d49fc796d
2 changed files with 12 additions and 19 deletions

View File

@@ -996,24 +996,17 @@ proc nl(s: var string, ml: bool) =
proc escapeJson*(s: string; result: var string) =
## Converts a string `s` to its JSON representation.
## Appends to ``result``.
const
HexChars = "0123456789ABCDEF"
result.add("\"")
for x in runes(s):
var r = int(x)
if r >= 32 and r <= 126:
var c = chr(r)
case c
of '"': result.add("\\\"")
of '\\': result.add("\\\\")
else: result.add(c)
else:
# toHex inlined for more speed (saves stupid string allocations):
result.add("\\u0000")
let start = result.len - 4
for j in countdown(3, 0):
result[j+start] = HexChars[r and 0xF]
r = r shr 4
for c in s:
case c
of '\L': result.add("\\n")
of '\b': result.add("\\b")
of '\f': result.add("\\f")
of '\t': result.add("\\t")
of '\r': result.add("\\r")
of '"': result.add("\\\"")
of '\\': result.add("\\\\")
else: result.add(c)
result.add("\"")
proc escapeJson*(s: string): string =
@@ -1925,7 +1918,7 @@ when isMainModule:
var parsed2 = parseFile("tests/testdata/jsontest2.json")
doAssert(parsed2{"repository", "description"}.str=="IRC Library for Haskell", "Couldn't fetch via multiply nested key using {}")
doAssert escapeJson("\10FoobarÄ") == "\"\\u000AFoobar\\u00C4\""
doAssert escapeJson("\10Foo🎃barÄ") == "\"\\nFoo🎃barÄ\""
# Test with extra data
when not defined(js):

View File

@@ -1,5 +1,5 @@
discard """
output: '''{"age": 12, "bio": "\u042F Cletus", "blob": [65, 66, 67, 128], "name": "Cletus"}
output: '''{"age": 12, "bio": "Я Cletus", "blob": [65, 66, 67, 128], "name": "Cletus"}
true
true
alpha 100