summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorhlaaf <hlaaftana@users.noreply.github.com>2018-08-27 13:22:55 +0300
committerAndreas Rumpf <rumpf_a@web.de>2018-08-27 12:22:55 +0200
commita2708995023307d5da04ed44d2b915495790a31a (patch)
tree9c8b5dee7081ce0d52f5343dc1554a24ceb9b9d9
parent3999e3be5fcf6df918e427c58b3c99b28a100cdd (diff)
downloadNim-a2708995023307d5da04ed44d2b915495790a31a.tar.gz
Add escapeJsonUnquoted for json escaped strings without quotes (#8785)
* Add escapeJsonUnquoted

* Add tests for escapeJsonUnquoted
-rw-r--r--lib/pure/json.nim20
1 files changed, 16 insertions, 4 deletions
diff --git a/lib/pure/json.nim b/lib/pure/json.nim
index 3599667a8..9279fea77 100644
--- a/lib/pure/json.nim
+++ b/lib/pure/json.nim
@@ -545,10 +545,9 @@ proc newIndent(curr, indent: int, ml: bool): int =
 proc nl(s: var string, ml: bool) =
   s.add(if ml: "\n" else: " ")
 
-proc escapeJson*(s: string; result: var string) =
-  ## Converts a string `s` to its JSON representation.
+proc escapeJsonUnquoted*(s: string; result: var string) =
+  ## Converts a string `s` to its JSON representation without quotes.
   ## Appends to ``result``.
-  result.add("\"")
   for c in s:
     case c
     of '\L': result.add("\\n")
@@ -561,10 +560,21 @@ proc escapeJson*(s: string; result: var string) =
     of '\14'..'\31': result.add("\\u00" & $ord(c))
     of '\\': result.add("\\\\")
     else: result.add(c)
+
+proc escapeJsonUnquoted*(s: string): string =
+  ## Converts a string `s` to its JSON representation without quotes.
+  result = newStringOfCap(s.len + s.len shr 3)
+  escapeJsonUnquoted(s, result)
+
+proc escapeJson*(s: string; result: var string) =
+  ## Converts a string `s` to its JSON representation with quotes.
+  ## Appends to ``result``.
+  result.add("\"")
+  escapeJsonUnquoted(s, result)
   result.add("\"")
 
 proc escapeJson*(s: string): string =
-  ## Converts a string `s` to its JSON representation.
+  ## Converts a string `s` to its JSON representation with quotes.
   result = newStringOfCap(s.len + s.len shr 3)
   escapeJson(s, result)
 
@@ -1607,6 +1617,8 @@ 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 escapeJsonUnquoted("\10Foo🎃barÄ") == "\\nFoo🎃barÄ"
+  doAssert escapeJsonUnquoted("\0\7\20") == "\\u0000\\u0007\\u0020" # for #7887
   doAssert escapeJson("\10Foo🎃barÄ") == "\"\\nFoo🎃barÄ\""
   doAssert escapeJson("\0\7\20") == "\"\\u0000\\u0007\\u0020\"" # for #7887