Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 85 lines (72 sloc) 2.224 kb
fccc685 Initial open-source release
MLstate authored
1 (*
2 Copyright © 2011 MLstate
3
4 This file is part of OPA.
5
6 OPA is free software: you can redistribute it and/or modify it under the
7 terms of the GNU Affero General Public License, version 3, as published by
8 the Free Software Foundation.
9
10 OPA is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
13 more details.
14
15 You should have received a copy of the GNU Affero General Public License
16 along with OPA. If not, see <http://www.gnu.org/licenses/>.
17 *)
18 (* depends *)
19 module List = BaseList
20
21 (* shorthands *)
22 module J = JsonTypes
23
24 (* -- *)
25
26 module type Printer =
27 sig
28 type t
29 val json : t -> JsonTypes.json -> unit
30 end
31
32 let escape_non_utf8_special s =
33 let reg_rep_list = [
34 Str.regexp "\\", "\\\\\\\\";
35 Str.regexp "\"", "\\\\\"";
36 Str.regexp "\n" , "\\\\n";
37 Str.regexp "\r" , "\\\\r";
38 Str.regexp "\t" , "\\\\t";
39 ] in
40 List.fold_left
41 (fun str (reg,rep) ->
42 Str.global_replace reg rep str) s reg_rep_list
43
44 let print add arg formule =
45 let add x = add arg x in
46 let rec aux = function
47 | J.Int n -> add (string_of_int n)
48 | J.Float f -> add (Printf.sprintf "%f" f)
49 | J.String s -> add ("\""^(escape_non_utf8_special s)^"\"")
50 | J.Bool b -> add (string_of_bool b)
51 | J.Void -> add "{}"
52 | J.Array jlst ->
53 add "[";
54 let length = List.length jlst - 1 in
55 List.iteri (fun x i -> aux x; if i < length then add ",") jlst;
56 add "]";
57 | J.Record sjlst ->
58 add "{";
59 let aux_field (n, x) =
60 add "\""; add n; add "\":"; aux x in
61 let rec aux = function
62 | [x] -> aux_field x
63 | t::q -> aux_field t; add ","; aux q
64 | _ -> ()
65 in aux sjlst; add "}"
66 in
67 aux formule
68
69 let to_string json =
70 let fb = Buffer.create 50 in
71 print Buffer.add_string fb json ;
72 Buffer.contents fb
73
74 module Output =
75 struct
76 type t = out_channel
77 let json oc json = print Pervasives.output_string oc json
78 end
79
80 module Buffer =
81 struct
82 type t = Buffer.t
83 let json buf json = print Buffer.add_string buf json
84 end
Something went wrong with that request. Please try again.