summary refs log tree commit diff stats
path: root/lib/pure
diff options
context:
space:
mode:
authorYuriy Glukhov <yglukhov@users.noreply.github.com>2017-09-15 11:53:58 +0300
committerAndreas Rumpf <rumpf_a@web.de>2017-09-15 10:53:58 +0200
commit7d49fc796da309afd426c62ba4c57d49e8e3a530 (patch)
tree8d511235604acfdcb42984c555bab817ea93783b /lib/pure
parent034e6a346824aaa874a2f42adf0d410e742b5ce1 (diff)
downloadNim-7d49fc796da309afd426c62ba4c57d49e8e3a530.tar.gz
Changed JSON stringification to preserve UTF (#6330)
Diffstat (limited to 'lib/pure')
-rw-r--r--lib/pure/json.nim29
1 files changed, 11 insertions, 18 deletions
diff --git a/lib/pure/json.nim b/lib/pure/json.nim
index 9dc9b51f3..097952588 100644
--- a/lib/pure/json.nim
+++ b/lib/pure/json.nim
@@ -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):