From 4040f5a404076b457827dc4322feb908e32e2f18 Mon Sep 17 00:00:00 2001 From: milner Date: Mon, 23 May 2022 21:14:56 +0000 Subject: [PATCH] feat(json): emit JSON with correct control-character escaping So generated output survives paths containing spaces, quotes or backslashes. --- lib/json.ml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 lib/json.ml diff --git a/lib/json.ml b/lib/json.ml new file mode 100644 index 0000000..8fab3ef --- /dev/null +++ b/lib/json.ml @@ -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) ^ "]"