feat(json): emit JSON with correct control-character escaping

So generated output survives paths containing spaces, quotes or backslashes.
This commit is contained in:
sneeker committed 2022-05-23 21:14:56 +00:00
1 parent 598ccfd4c0
commit b48cd708a4
1 file changed
+17
+17
View File
@@ -0,0 +1,17 @@
let escape s =
let b = Buffer.create (String.length s + 8) in
String.iter
(fun c ->
match c with
| '"' -> Buffer.add_string b "\\\""
| '\\' -> Buffer.add_string b "\\\\"
| '\n' -> Buffer.add_string b "\\n"
| '\t' -> Buffer.add_string b "\\t"
| '\r' -> Buffer.add_string b "\\r"
| c when Char.code c < 0x20 -> Buffer.add_string b (Printf.sprintf "\\u%04x" (Char.code c))
| c -> Buffer.add_char b c)
s;
Buffer.contents b
let str s = "\"" ^ escape s ^ "\""
let list f l = "[" ^ String.concat ", " (List.map f l) ^ "]"