Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 530 lines (475 sloc) 19.107 kb
4842019 @mdempsky first post
mdempsky authored
1 %% @author Bob Ippolito <bob@mochimedia.com>
2 %% @copyright 2006 Mochi Media, Inc.
3
4 %% @doc Yet another JSON (RFC 4627) library for Erlang.
5 -module(mochijson).
6 -author('bob@mochimedia.com').
7 -export([encoder/1, encode/1]).
8 -export([decoder/1, decode/1]).
09c9099 @etrepum bring mochijson2 API into mochijson as binary_*
etrepum authored
9 -export([binary_encoder/1, binary_encode/1]).
10 -export([binary_decoder/1, binary_decode/1]).
4842019 @mdempsky first post
mdempsky authored
11 -export([test/0]).
12
13 % This is a macro to placate syntax highlighters..
14 -define(Q, $\").
15 -define(ADV_COL(S, N), S#decoder{column=N+S#decoder.column}).
16 -define(INC_COL(S), S#decoder{column=1+S#decoder.column}).
17 -define(INC_LINE(S), S#decoder{column=1, line=1+S#decoder.line}).
18
19 %% @type iolist() = [char() | binary() | iolist()]
20 %% @type iodata() = iolist() | binary()
21 %% @type json_string() = atom | string() | binary()
22 %% @type json_number() = integer() | float()
23 %% @type json_array() = {array, [json_term()]}
24 %% @type json_object() = {struct, [{json_string(), json_term()}]}
25 %% @type json_term() = json_string() | json_number() | json_array() |
26 %% json_object()
27 %% @type encoding() = utf8 | unicode
28 %% @type encoder_option() = {input_encoding, encoding()} |
29 %% {handler, function()}
30 %% @type decoder_option() = {input_encoding, encoding()} |
31 %% {object_hook, function()}
09c9099 @etrepum bring mochijson2 API into mochijson as binary_*
etrepum authored
32 %% @type bjson_string() = binary()
33 %% @type bjson_number() = integer() | float()
34 %% @type bjson_array() = [bjson_term()]
35 %% @type bjson_object() = {struct, [{bjson_string(), bjson_term()}]}
36 %% @type bjson_term() = bjson_string() | bjson_number() | bjson_array() |
37 %% bjson_object()
38 %% @type binary_encoder_option() = {handler, function()}
39 %% @type binary_decoder_option() = {object_hook, function()}
4842019 @mdempsky first post
mdempsky authored
40
41 -record(encoder, {input_encoding=unicode,
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
42 handler=null}).
4842019 @mdempsky first post
mdempsky authored
43
44 -record(decoder, {input_encoding=utf8,
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
45 object_hook=null,
46 line=1,
47 column=1,
48 state=null}).
4842019 @mdempsky first post
mdempsky authored
49
50 %% @spec encoder([encoder_option()]) -> function()
51 %% @doc Create an encoder/1 with the given options.
52 encoder(Options) ->
53 State = parse_encoder_options(Options, #encoder{}),
54 fun (O) -> json_encode(O, State) end.
55
56 %% @spec encode(json_term()) -> iolist()
57 %% @doc Encode the given as JSON to an iolist.
58 encode(Any) ->
59 json_encode(Any, #encoder{}).
60
61 %% @spec decoder([decoder_option()]) -> function()
62 %% @doc Create a decoder/1 with the given options.
63 decoder(Options) ->
64 State = parse_decoder_options(Options, #decoder{}),
65 fun (O) -> json_decode(O, State) end.
66
67 %% @spec decode(iolist()) -> json_term()
68 %% @doc Decode the given iolist to Erlang terms.
69 decode(S) ->
70 json_decode(S, #decoder{}).
71
09c9099 @etrepum bring mochijson2 API into mochijson as binary_*
etrepum authored
72 %% @spec binary_decoder([binary_decoder_option()]) -> function()
73 %% @doc Create a binary_decoder/1 with the given options.
74 binary_decoder(Options) ->
75 mochijson2:decoder(Options).
76
77 %% @spec binary_encoder([binary_encoder_option()]) -> function()
78 %% @doc Create a binary_encoder/1 with the given options.
79 binary_encoder(Options) ->
80 mochijson2:encoder(Options).
81
82 %% @spec binary_encode(bjson_term()) -> iolist()
83 %% @doc Encode the given as JSON to an iolist, using lists for arrays and
84 %% binaries for strings.
85 binary_encode(Any) ->
86 mochijson2:encode(Any).
87
88 %% @spec binary_decode(iolist()) -> bjson_term()
89 %% @doc Decode the given iolist to Erlang terms, using lists for arrays and
90 %% binaries for strings.
91 binary_decode(S) ->
92 mochijson2:decode(S).
93
4842019 @mdempsky first post
mdempsky authored
94 test() ->
09c9099 @etrepum bring mochijson2 API into mochijson as binary_*
etrepum authored
95 test_all(),
96 mochijson2:test().
4842019 @mdempsky first post
mdempsky authored
97
98 %% Internal API
99
100 parse_encoder_options([], State) ->
101 State;
102 parse_encoder_options([{input_encoding, Encoding} | Rest], State) ->
103 parse_encoder_options(Rest, State#encoder{input_encoding=Encoding});
104 parse_encoder_options([{handler, Handler} | Rest], State) ->
105 parse_encoder_options(Rest, State#encoder{handler=Handler}).
106
107 parse_decoder_options([], State) ->
108 State;
109 parse_decoder_options([{input_encoding, Encoding} | Rest], State) ->
110 parse_decoder_options(Rest, State#decoder{input_encoding=Encoding});
111 parse_decoder_options([{object_hook, Hook} | Rest], State) ->
112 parse_decoder_options(Rest, State#decoder{object_hook=Hook}).
113
114 json_encode(true, _State) ->
115 "true";
116 json_encode(false, _State) ->
117 "false";
118 json_encode(null, _State) ->
119 "null";
120 json_encode(I, _State) when is_integer(I) ->
121 integer_to_list(I);
122 json_encode(F, _State) when is_float(F) ->
cd3fcd8 @etrepum use mochinum even in 'legacy' mochijson
etrepum authored
123 mochinum:digits(F);
4842019 @mdempsky first post
mdempsky authored
124 json_encode(L, State) when is_list(L); is_binary(L); is_atom(L) ->
125 json_encode_string(L, State);
126 json_encode({array, Props}, State) when is_list(Props) ->
127 json_encode_array(Props, State);
128 json_encode({struct, Props}, State) when is_list(Props) ->
129 json_encode_proplist(Props, State);
130 json_encode(Bad, #encoder{handler=null}) ->
131 exit({json_encode, {bad_term, Bad}});
132 json_encode(Bad, State=#encoder{handler=Handler}) ->
133 json_encode(Handler(Bad), State).
134
135 json_encode_array([], _State) ->
136 "[]";
137 json_encode_array(L, State) ->
138 F = fun (O, Acc) ->
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
139 [$,, json_encode(O, State) | Acc]
140 end,
4842019 @mdempsky first post
mdempsky authored
141 [$, | Acc1] = lists:foldl(F, "[", L),
142 lists:reverse([$\] | Acc1]).
143
144 json_encode_proplist([], _State) ->
145 "{}";
146 json_encode_proplist(Props, State) ->
147 F = fun ({K, V}, Acc) ->
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
148 KS = case K of
149 K when is_atom(K) ->
150 json_encode_string_utf8(atom_to_list(K));
151 K when is_integer(K) ->
152 json_encode_string(integer_to_list(K), State);
153 K when is_list(K); is_binary(K) ->
154 json_encode_string(K, State)
155 end,
156 VS = json_encode(V, State),
157 [$,, VS, $:, KS | Acc]
158 end,
4842019 @mdempsky first post
mdempsky authored
159 [$, | Acc1] = lists:foldl(F, "{", Props),
160 lists:reverse([$\} | Acc1]).
161
162 json_encode_string(A, _State) when is_atom(A) ->
2b76820 @etrepum sync with internal version
etrepum authored
163 json_encode_string_unicode(xmerl_ucs:from_utf8(atom_to_list(A)));
4842019 @mdempsky first post
mdempsky authored
164 json_encode_string(B, _State) when is_binary(B) ->
2b76820 @etrepum sync with internal version
etrepum authored
165 json_encode_string_unicode(xmerl_ucs:from_utf8(B));
4842019 @mdempsky first post
mdempsky authored
166 json_encode_string(S, #encoder{input_encoding=utf8}) ->
2b76820 @etrepum sync with internal version
etrepum authored
167 json_encode_string_utf8(S);
4842019 @mdempsky first post
mdempsky authored
168 json_encode_string(S, #encoder{input_encoding=unicode}) ->
2b76820 @etrepum sync with internal version
etrepum authored
169 json_encode_string_unicode(S).
170
171 json_encode_string_utf8(S) ->
172 [?Q | json_encode_string_utf8_1(S)].
173
174 json_encode_string_utf8_1([C | Cs]) when C >= 0, C =< 16#7f ->
175 NewC = case C of
176 $\\ -> "\\\\";
3ec0a2d @mdempsky add more string encoding/decoding test cases for mochijson/mochijson2…
mdempsky authored
177 ?Q -> "\\\"";
07c37bf @mdempsky fix misencoding of backslash characters; add regression test case for…
mdempsky authored
178 _ when C >= $\s, C < 16#7f -> C;
2b76820 @etrepum sync with internal version
etrepum authored
179 $\t -> "\\t";
180 $\n -> "\\n";
181 $\r -> "\\r";
182 $\f -> "\\f";
183 $\b -> "\\b";
184 _ when C >= 0, C =< 16#7f -> unihex(C);
185 _ -> exit({json_encode, {bad_char, C}})
186 end,
187 [NewC | json_encode_string_utf8_1(Cs)];
188 json_encode_string_utf8_1(All=[C | _]) when C >= 16#80, C =< 16#10FFFF ->
189 json_encode_string_unicode(xmerl_ucs:from_utf8(All));
190 json_encode_string_utf8_1([]) ->
191 "\"".
192
193 json_encode_string_unicode(S) ->
194 [?Q | json_encode_string_unicode_1(S)].
195
196 json_encode_string_unicode_1([C | Cs]) ->
197 NewC = case C of
198 $\\ -> "\\\\";
3ec0a2d @mdempsky add more string encoding/decoding test cases for mochijson/mochijson2…
mdempsky authored
199 ?Q -> "\\\"";
07c37bf @mdempsky fix misencoding of backslash characters; add regression test case for…
mdempsky authored
200 _ when C >= $\s, C < 16#7f -> C;
2b76820 @etrepum sync with internal version
etrepum authored
201 $\t -> "\\t";
202 $\n -> "\\n";
203 $\r -> "\\r";
204 $\f -> "\\f";
205 $\b -> "\\b";
206 _ when C >= 0, C =< 16#10FFFF -> unihex(C);
207 _ -> exit({json_encode, {bad_char, C}})
208 end,
209 [NewC | json_encode_string_unicode_1(Cs)];
210 json_encode_string_unicode_1([]) ->
211 "\"".
4842019 @mdempsky first post
mdempsky authored
212
213 dehex(C) when C >= $0, C =< $9 ->
214 C - $0;
215 dehex(C) when C >= $a, C =< $f ->
216 C - $a + 10;
217 dehex(C) when C >= $A, C =< $F ->
218 C - $A + 10.
219
220 hexdigit(C) when C >= 0, C =< 9 ->
221 C + $0;
222 hexdigit(C) when C =< 15 ->
223 C + $a - 10.
224
225 unihex(C) when C < 16#10000 ->
226 <<D3:4, D2:4, D1:4, D0:4>> = <<C:16>>,
227 Digits = [hexdigit(D) || D <- [D3, D2, D1, D0]],
228 [$\\, $u | Digits];
229 unihex(C) when C =< 16#10FFFF ->
230 N = C - 16#10000,
231 S1 = 16#d800 bor ((N bsr 10) band 16#3ff),
232 S2 = 16#dc00 bor (N band 16#3ff),
233 [unihex(S1), unihex(S2)].
234
235 json_decode(B, S) when is_binary(B) ->
bfa4b12 @etrepum fix mochijson UTF-8 issue with decoding binaries
etrepum authored
236 json_decode(binary_to_list(B), S);
4842019 @mdempsky first post
mdempsky authored
237 json_decode(L, S) ->
238 {Res, L1, S1} = decode1(L, S),
239 {eof, [], _} = tokenize(L1, S1#decoder{state=trim}),
240 Res.
241
242 decode1(L, S=#decoder{state=null}) ->
243 case tokenize(L, S#decoder{state=any}) of
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
244 {{const, C}, L1, S1} ->
245 {C, L1, S1};
246 {start_array, L1, S1} ->
247 decode_array(L1, S1#decoder{state=any}, []);
248 {start_object, L1, S1} ->
249 decode_object(L1, S1#decoder{state=key}, [])
4842019 @mdempsky first post
mdempsky authored
250 end.
251
252 make_object(V, #decoder{object_hook=null}) ->
253 V;
254 make_object(V, #decoder{object_hook=Hook}) ->
255 Hook(V).
256
257 decode_object(L, S=#decoder{state=key}, Acc) ->
258 case tokenize(L, S) of
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
259 {end_object, Rest, S1} ->
260 V = make_object({struct, lists:reverse(Acc)}, S1),
261 {V, Rest, S1#decoder{state=null}};
262 {{const, K}, Rest, S1} when is_list(K) ->
263 {colon, L2, S2} = tokenize(Rest, S1),
264 {V, L3, S3} = decode1(L2, S2#decoder{state=null}),
265 decode_object(L3, S3#decoder{state=comma}, [{K, V} | Acc])
4842019 @mdempsky first post
mdempsky authored
266 end;
267 decode_object(L, S=#decoder{state=comma}, Acc) ->
268 case tokenize(L, S) of
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
269 {end_object, Rest, S1} ->
270 V = make_object({struct, lists:reverse(Acc)}, S1),
271 {V, Rest, S1#decoder{state=null}};
272 {comma, Rest, S1} ->
273 decode_object(Rest, S1#decoder{state=key}, Acc)
4842019 @mdempsky first post
mdempsky authored
274 end.
275
276 decode_array(L, S=#decoder{state=any}, Acc) ->
277 case tokenize(L, S) of
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
278 {end_array, Rest, S1} ->
279 {{array, lists:reverse(Acc)}, Rest, S1#decoder{state=null}};
280 {start_array, Rest, S1} ->
281 {Array, Rest1, S2} = decode_array(Rest, S1#decoder{state=any}, []),
282 decode_array(Rest1, S2#decoder{state=comma}, [Array | Acc]);
283 {start_object, Rest, S1} ->
284 {Array, Rest1, S2} = decode_object(Rest, S1#decoder{state=key}, []),
285 decode_array(Rest1, S2#decoder{state=comma}, [Array | Acc]);
286 {{const, Const}, Rest, S1} ->
287 decode_array(Rest, S1#decoder{state=comma}, [Const | Acc])
4842019 @mdempsky first post
mdempsky authored
288 end;
289 decode_array(L, S=#decoder{state=comma}, Acc) ->
290 case tokenize(L, S) of
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
291 {end_array, Rest, S1} ->
292 {{array, lists:reverse(Acc)}, Rest, S1#decoder{state=null}};
293 {comma, Rest, S1} ->
294 decode_array(Rest, S1#decoder{state=any}, Acc)
4842019 @mdempsky first post
mdempsky authored
295 end.
296
297 tokenize_string(IoList=[C | _], S=#decoder{input_encoding=utf8}, Acc)
298 when is_list(C); is_binary(C); C >= 16#7f ->
299 List = xmerl_ucs:from_utf8(iolist_to_binary(IoList)),
300 tokenize_string(List, S#decoder{input_encoding=unicode}, Acc);
301 tokenize_string("\"" ++ Rest, S, Acc) ->
302 {lists:reverse(Acc), Rest, ?INC_COL(S)};
303 tokenize_string("\\\"" ++ Rest, S, Acc) ->
304 tokenize_string(Rest, ?ADV_COL(S, 2), [$\" | Acc]);
305 tokenize_string("\\\\" ++ Rest, S, Acc) ->
306 tokenize_string(Rest, ?ADV_COL(S, 2), [$\\ | Acc]);
307 tokenize_string("\\/" ++ Rest, S, Acc) ->
308 tokenize_string(Rest, ?ADV_COL(S, 2), [$/ | Acc]);
309 tokenize_string("\\b" ++ Rest, S, Acc) ->
310 tokenize_string(Rest, ?ADV_COL(S, 2), [$\b | Acc]);
311 tokenize_string("\\f" ++ Rest, S, Acc) ->
3ec0a2d @mdempsky add more string encoding/decoding test cases for mochijson/mochijson2…
mdempsky authored
312 tokenize_string(Rest, ?ADV_COL(S, 2), [$\f | Acc]);
4842019 @mdempsky first post
mdempsky authored
313 tokenize_string("\\n" ++ Rest, S, Acc) ->
314 tokenize_string(Rest, ?ADV_COL(S, 2), [$\n | Acc]);
315 tokenize_string("\\r" ++ Rest, S, Acc) ->
316 tokenize_string(Rest, ?ADV_COL(S, 2), [$\r | Acc]);
317 tokenize_string("\\t" ++ Rest, S, Acc) ->
318 tokenize_string(Rest, ?ADV_COL(S, 2), [$\t | Acc]);
319 tokenize_string([$\\, $u, C3, C2, C1, C0 | Rest], S, Acc) ->
320 % coalesce UTF-16 surrogate pair?
321 C = dehex(C0) bor
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
322 (dehex(C1) bsl 4) bor
323 (dehex(C2) bsl 8) bor
324 (dehex(C3) bsl 12),
4842019 @mdempsky first post
mdempsky authored
325 tokenize_string(Rest, ?ADV_COL(S, 6), [C | Acc]);
326 tokenize_string([C | Rest], S, Acc) when C >= $\s; C < 16#10FFFF ->
327 tokenize_string(Rest, ?ADV_COL(S, 1), [C | Acc]).
328
329 tokenize_number(IoList=[C | _], Mode, S=#decoder{input_encoding=utf8}, Acc)
330 when is_list(C); is_binary(C); C >= 16#7f ->
331 List = xmerl_ucs:from_utf8(iolist_to_binary(IoList)),
332 tokenize_number(List, Mode, S#decoder{input_encoding=unicode}, Acc);
333 tokenize_number([$- | Rest], sign, S, []) ->
334 tokenize_number(Rest, int, ?INC_COL(S), [$-]);
335 tokenize_number(Rest, sign, S, []) ->
336 tokenize_number(Rest, int, S, []);
337 tokenize_number([$0 | Rest], int, S, Acc) ->
338 tokenize_number(Rest, frac, ?INC_COL(S), [$0 | Acc]);
339 tokenize_number([C | Rest], int, S, Acc) when C >= $1, C =< $9 ->
340 tokenize_number(Rest, int1, ?INC_COL(S), [C | Acc]);
341 tokenize_number([C | Rest], int1, S, Acc) when C >= $0, C =< $9 ->
342 tokenize_number(Rest, int1, ?INC_COL(S), [C | Acc]);
343 tokenize_number(Rest, int1, S, Acc) ->
344 tokenize_number(Rest, frac, S, Acc);
345 tokenize_number([$., C | Rest], frac, S, Acc) when C >= $0, C =< $9 ->
346 tokenize_number(Rest, frac1, ?ADV_COL(S, 2), [C, $. | Acc]);
347 tokenize_number([E | Rest], frac, S, Acc) when E == $e; E == $E ->
348 tokenize_number(Rest, esign, ?INC_COL(S), [$e, $0, $. | Acc]);
349 tokenize_number(Rest, frac, S, Acc) ->
350 {{int, lists:reverse(Acc)}, Rest, S};
351 tokenize_number([C | Rest], frac1, S, Acc) when C >= $0, C =< $9 ->
352 tokenize_number(Rest, frac1, ?INC_COL(S), [C | Acc]);
353 tokenize_number([E | Rest], frac1, S, Acc) when E == $e; E == $E ->
354 tokenize_number(Rest, esign, ?INC_COL(S), [$e | Acc]);
355 tokenize_number(Rest, frac1, S, Acc) ->
356 {{float, lists:reverse(Acc)}, Rest, S};
357 tokenize_number([C | Rest], esign, S, Acc) when C == $-; C == $+ ->
358 tokenize_number(Rest, eint, ?INC_COL(S), [C | Acc]);
359 tokenize_number(Rest, esign, S, Acc) ->
360 tokenize_number(Rest, eint, S, Acc);
361 tokenize_number([C | Rest], eint, S, Acc) when C >= $0, C =< $9 ->
362 tokenize_number(Rest, eint1, ?INC_COL(S), [C | Acc]);
363 tokenize_number([C | Rest], eint1, S, Acc) when C >= $0, C =< $9 ->
364 tokenize_number(Rest, eint1, ?INC_COL(S), [C | Acc]);
365 tokenize_number(Rest, eint1, S, Acc) ->
366 {{float, lists:reverse(Acc)}, Rest, S}.
367
368 tokenize([], S=#decoder{state=trim}) ->
369 {eof, [], S};
370 tokenize([L | Rest], S) when is_list(L) ->
371 tokenize(L ++ Rest, S);
372 tokenize([B | Rest], S) when is_binary(B) ->
373 tokenize(xmerl_ucs:from_utf8(B) ++ Rest, S);
374 tokenize("\r\n" ++ Rest, S) ->
375 tokenize(Rest, ?INC_LINE(S));
376 tokenize("\n" ++ Rest, S) ->
377 tokenize(Rest, ?INC_LINE(S));
378 tokenize([C | Rest], S) when C == $\s; C == $\t ->
379 tokenize(Rest, ?INC_COL(S));
380 tokenize("{" ++ Rest, S) ->
381 {start_object, Rest, ?INC_COL(S)};
382 tokenize("}" ++ Rest, S) ->
383 {end_object, Rest, ?INC_COL(S)};
384 tokenize("[" ++ Rest, S) ->
385 {start_array, Rest, ?INC_COL(S)};
386 tokenize("]" ++ Rest, S) ->
387 {end_array, Rest, ?INC_COL(S)};
388 tokenize("," ++ Rest, S) ->
389 {comma, Rest, ?INC_COL(S)};
390 tokenize(":" ++ Rest, S) ->
391 {colon, Rest, ?INC_COL(S)};
392 tokenize("null" ++ Rest, S) ->
393 {{const, null}, Rest, ?ADV_COL(S, 4)};
394 tokenize("true" ++ Rest, S) ->
395 {{const, true}, Rest, ?ADV_COL(S, 4)};
396 tokenize("false" ++ Rest, S) ->
397 {{const, false}, Rest, ?ADV_COL(S, 5)};
398 tokenize("\"" ++ Rest, S) ->
399 {String, Rest1, S1} = tokenize_string(Rest, ?INC_COL(S), []),
400 {{const, String}, Rest1, S1};
401 tokenize(L=[C | _], S) when C >= $0, C =< $9; C == $- ->
402 case tokenize_number(L, sign, S, []) of
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
403 {{int, Int}, Rest, S1} ->
404 {{const, list_to_integer(Int)}, Rest, S1};
405 {{float, Float}, Rest, S1} ->
406 {{const, list_to_float(Float)}, Rest, S1}
4842019 @mdempsky first post
mdempsky authored
407 end.
408
409 %% testing constructs borrowed from the Yaws JSON implementation.
410
411 %% Create an object from a list of Key/Value pairs.
412
413 obj_new() ->
414 {struct, []}.
415
416 is_obj({struct, Props}) ->
417 F = fun ({K, _}) when is_list(K) ->
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
418 true;
419 (_) ->
420 false
421 end,
4842019 @mdempsky first post
mdempsky authored
422 lists:all(F, Props).
423
424 obj_from_list(Props) ->
425 Obj = {struct, Props},
426 case is_obj(Obj) of
427 true -> Obj;
428 false -> exit(json_bad_object)
429 end.
430
431 %% Test for equivalence of Erlang terms.
432 %% Due to arbitrary order of construction, equivalent objects might
433 %% compare unequal as erlang terms, so we need to carefully recurse
434 %% through aggregates (tuples and objects).
435
436 equiv({struct, Props1}, {struct, Props2}) ->
437 equiv_object(Props1, Props2);
438 equiv({array, L1}, {array, L2}) ->
439 equiv_list(L1, L2);
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
440 equiv(N1, N2) when is_number(N1), is_number(N2) -> N1 == N2;
441 equiv(S1, S2) when is_list(S1), is_list(S2) -> S1 == S2;
4842019 @mdempsky first post
mdempsky authored
442 equiv(true, true) -> true;
443 equiv(false, false) -> true;
444 equiv(null, null) -> true.
445
446 %% Object representation and traversal order is unknown.
447 %% Use the sledgehammer and sort property lists.
448
449 equiv_object(Props1, Props2) ->
450 L1 = lists:keysort(1, Props1),
451 L2 = lists:keysort(1, Props2),
452 Pairs = lists:zip(L1, L2),
453 true = lists:all(fun({{K1, V1}, {K2, V2}}) ->
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
454 equiv(K1, K2) and equiv(V1, V2)
4842019 @mdempsky first post
mdempsky authored
455 end, Pairs).
456
457 %% Recursively compare tuple elements for equivalence.
458
459 equiv_list([], []) ->
460 true;
461 equiv_list([V1 | L1], [V2 | L2]) ->
462 case equiv(V1, V2) of
3f7ef81 @etrepum detab source, chunked-like responses for HTTP/1.0 clients
etrepum authored
463 true ->
464 equiv_list(L1, L2);
465 false ->
466 false
4842019 @mdempsky first post
mdempsky authored
467 end.
468
469 test_all() ->
470 test_one(e2j_test_vec(utf8), 1).
471
472 test_one([], _N) ->
473 %% io:format("~p tests passed~n", [N-1]),
474 ok;
475 test_one([{E, J} | Rest], N) ->
476 %% io:format("[~p] ~p ~p~n", [N, E, J]),
477 true = equiv(E, decode(J)),
478 true = equiv(E, decode(encode(E))),
479 test_one(Rest, 1+N).
480
481 e2j_test_vec(unicode) ->
482 [
483 {"foo" ++ [500] ++ "bar", [$", $f, $o, $o, 500, $b, $a, $r, $"]}
484 ];
485 e2j_test_vec(utf8) ->
486 [
487 {1, "1"},
488 {3.1416, "3.14160"}, % text representation may truncate, trail zeroes
489 {-1, "-1"},
490 {-3.1416, "-3.14160"},
491 {12.0e10, "1.20000e+11"},
492 {1.234E+10, "1.23400e+10"},
493 {-1.234E-10, "-1.23400e-10"},
494 {10.0, "1.0e+01"},
495 {123.456, "1.23456E+2"},
496 {10.0, "1e1"},
497 {"foo", "\"foo\""},
498 {"foo" ++ [5] ++ "bar", "\"foo\\u0005bar\""},
499 {"", "\"\""},
3ec0a2d @mdempsky add more string encoding/decoding test cases for mochijson/mochijson2…
mdempsky authored
500 {"\"", "\"\\\"\""},
4842019 @mdempsky first post
mdempsky authored
501 {"\n\n\n", "\"\\n\\n\\n\""},
07c37bf @mdempsky fix misencoding of backslash characters; add regression test case for…
mdempsky authored
502 {"\\", "\"\\\\\""},
3ec0a2d @mdempsky add more string encoding/decoding test cases for mochijson/mochijson2…
mdempsky authored
503 {"\" \b\f\r\n\t\"", "\"\\\" \\b\\f\\r\\n\\t\\\"\""},
4842019 @mdempsky first post
mdempsky authored
504 {obj_new(), "{}"},
505 {obj_from_list([{"foo", "bar"}]), "{\"foo\":\"bar\"}"},
506 {obj_from_list([{"foo", "bar"}, {"baz", 123}]),
507 "{\"foo\":\"bar\",\"baz\":123}"},
508 {{array, []}, "[]"},
509 {{array, [{array, []}]}, "[[]]"},
510 {{array, [1, "foo"]}, "[1,\"foo\"]"},
511
512 % json array in a json object
513 {obj_from_list([{"foo", {array, [123]}}]),
514 "{\"foo\":[123]}"},
515
516 % json object in a json object
517 {obj_from_list([{"foo", obj_from_list([{"bar", true}])}]),
518 "{\"foo\":{\"bar\":true}}"},
519
520 % fold evaluation order
521 {obj_from_list([{"foo", {array, []}},
522 {"bar", obj_from_list([{"baz", true}])},
523 {"alice", "bob"}]),
524 "{\"foo\":[],\"bar\":{\"baz\":true},\"alice\":\"bob\"}"},
525
526 % json object in a json array
527 {{array, [-123, "foo", obj_from_list([{"bar", {array, []}}]), null]},
528 "[-123,\"foo\",{\"bar\":[]},null]"}
529 ].
Something went wrong with that request. Please try again.