Files
meowc/lib/json.ml
T
milner 4040f5a404 feat(json): emit JSON with correct control-character escaping
So generated output survives paths containing spaces, quotes or backslashes.
2022-05-23 21:14:56 +00:00

18 lines
578 B
OCaml

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) ^ "]"