mirror of
https://github.com/nim-lang/Nim.git
synced 2026-07-19 15:31:28 +00:00
Changed JSON stringification to preserve UTF (#6330)
This commit is contained in:
committed by
Andreas Rumpf
parent
034e6a3468
commit
7d49fc796d
@@ -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):
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user