PageRenderTime 236ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/src/mochijson2.erl

http://github.com/basho/mochiweb
Erlang | 907 lines | 710 code | 74 blank | 123 comment | 9 complexity | c8b75f616697be8654d1ab377b016ab4 MD5 | raw file
Possible License(s): MIT
  1. %% @author Bob Ippolito <bob@mochimedia.com>
  2. %% @copyright 2007 Mochi Media, Inc.
  3. %%
  4. %% Permission is hereby granted, free of charge, to any person obtaining a
  5. %% copy of this software and associated documentation files (the "Software"),
  6. %% to deal in the Software without restriction, including without limitation
  7. %% the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. %% and/or sell copies of the Software, and to permit persons to whom the
  9. %% Software is furnished to do so, subject to the following conditions:
  10. %%
  11. %% The above copyright notice and this permission notice shall be included in
  12. %% all copies or substantial portions of the Software.
  13. %%
  14. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. %% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. %% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. %% DEALINGS IN THE SOFTWARE.
  21. %% @doc Yet another JSON (RFC 4627) library for Erlang. mochijson2 works
  22. %% with binaries as strings, arrays as lists (without an {array, _})
  23. %% wrapper and it only knows how to decode UTF-8 (and ASCII).
  24. %%
  25. %% JSON terms are decoded as follows (javascript -> erlang):
  26. %% <ul>
  27. %% <li>{"key": "value"} ->
  28. %% {struct, [{&lt;&lt;"key">>, &lt;&lt;"value">>}]}</li>
  29. %% <li>["array", 123, 12.34, true, false, null] ->
  30. %% [&lt;&lt;"array">>, 123, 12.34, true, false, null]
  31. %% </li>
  32. %% </ul>
  33. %% <ul>
  34. %% <li>Strings in JSON decode to UTF-8 binaries in Erlang</li>
  35. %% <li>Objects decode to {struct, PropList}</li>
  36. %% <li>Numbers decode to integer or float</li>
  37. %% <li>true, false, null decode to their respective terms.</li>
  38. %% </ul>
  39. %% The encoder will accept the same format that the decoder will produce,
  40. %% but will also allow additional cases for leniency:
  41. %% <ul>
  42. %% <li>atoms other than true, false, null will be considered UTF-8
  43. %% strings (even as a proplist key)
  44. %% </li>
  45. %% <li>{json, IoList} will insert IoList directly into the output
  46. %% with no validation
  47. %% </li>
  48. %% <li>{array, Array} will be encoded as Array
  49. %% (legacy mochijson style)
  50. %% </li>
  51. %% <li>A non-empty raw proplist will be encoded as an object as long
  52. %% as the first pair does not have an atom key of json, struct,
  53. %% or array
  54. %% </li>
  55. %% </ul>
  56. -module(mochijson2).
  57. -author('bob@mochimedia.com').
  58. -export([encoder/1, encode/1]).
  59. -export([decoder/1, decode/1, decode/2]).
  60. %% This is a macro to placate syntax highlighters..
  61. -define(Q, $\").
  62. -define(ADV_COL(S, N), S#decoder{offset=N+S#decoder.offset,
  63. column=N+S#decoder.column}).
  64. -define(INC_COL(S), S#decoder{offset=1+S#decoder.offset,
  65. column=1+S#decoder.column}).
  66. -define(INC_LINE(S), S#decoder{offset=1+S#decoder.offset,
  67. column=1,
  68. line=1+S#decoder.line}).
  69. -define(INC_CHAR(S, C),
  70. case C of
  71. $\n ->
  72. S#decoder{column=1,
  73. line=1+S#decoder.line,
  74. offset=1+S#decoder.offset};
  75. _ ->
  76. S#decoder{column=1+S#decoder.column,
  77. offset=1+S#decoder.offset}
  78. end).
  79. -define(IS_WHITESPACE(C),
  80. (C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)).
  81. %% @type json_string() = atom | binary()
  82. %% @type json_number() = integer() | float()
  83. %% @type json_array() = [json_term()]
  84. %% @type json_object() = {struct, [{json_string(), json_term()}]}
  85. %% @type json_eep18_object() = {[{json_string(), json_term()}]}
  86. %% @type json_iolist() = {json, iolist()}
  87. %% @type json_term() = json_string() | json_number() | json_array() |
  88. %% json_object() | json_eep18_object() | json_iolist()
  89. -record(encoder, {handler=null,
  90. utf8=false}).
  91. -record(decoder, {object_hook=null,
  92. offset=0,
  93. line=1,
  94. column=1,
  95. state=null}).
  96. %% @spec encoder([encoder_option()]) -> function()
  97. %% @doc Create an encoder/1 with the given options.
  98. %% @type encoder_option() = handler_option() | utf8_option()
  99. %% @type utf8_option() = boolean(). Emit unicode as utf8 (default - false)
  100. encoder(Options) ->
  101. State = parse_encoder_options(Options, #encoder{}),
  102. fun (O) -> json_encode(O, State) end.
  103. %% @spec encode(json_term()) -> iolist()
  104. %% @doc Encode the given as JSON to an iolist.
  105. encode(Any) ->
  106. json_encode(Any, #encoder{}).
  107. %% @spec decoder([decoder_option()]) -> function()
  108. %% @doc Create a decoder/1 with the given options.
  109. decoder(Options) ->
  110. State = parse_decoder_options(Options, #decoder{}),
  111. fun (O) -> json_decode(O, State) end.
  112. %% @spec decode(iolist(), [{format, proplist | eep18 | struct}]) -> json_term()
  113. %% @doc Decode the given iolist to Erlang terms using the given object format
  114. %% for decoding, where proplist returns JSON objects as [{binary(), json_term()}]
  115. %% proplists, eep18 returns JSON objects as {[binary(), json_term()]}, and struct
  116. %% returns them as-is.
  117. decode(S, Options) ->
  118. json_decode(S, parse_decoder_options(Options, #decoder{})).
  119. %% @spec decode(iolist()) -> json_term()
  120. %% @doc Decode the given iolist to Erlang terms.
  121. decode(S) ->
  122. json_decode(S, #decoder{}).
  123. %% Internal API
  124. parse_encoder_options([], State) ->
  125. State;
  126. parse_encoder_options([{handler, Handler} | Rest], State) ->
  127. parse_encoder_options(Rest, State#encoder{handler=Handler});
  128. parse_encoder_options([{utf8, Switch} | Rest], State) ->
  129. parse_encoder_options(Rest, State#encoder{utf8=Switch}).
  130. parse_decoder_options([], State) ->
  131. State;
  132. parse_decoder_options([{object_hook, Hook} | Rest], State) ->
  133. parse_decoder_options(Rest, State#decoder{object_hook=Hook});
  134. parse_decoder_options([{format, Format} | Rest], State)
  135. when Format =:= struct orelse Format =:= eep18 orelse Format =:= proplist ->
  136. parse_decoder_options(Rest, State#decoder{object_hook=Format}).
  137. json_encode(true, _State) ->
  138. <<"true">>;
  139. json_encode(false, _State) ->
  140. <<"false">>;
  141. json_encode(null, _State) ->
  142. <<"null">>;
  143. json_encode(I, _State) when is_integer(I) ->
  144. integer_to_list(I);
  145. json_encode(F, _State) when is_float(F) ->
  146. mochinum:digits(F);
  147. json_encode(S, State) when is_binary(S); is_atom(S) ->
  148. json_encode_string(S, State);
  149. json_encode([{K, _}|_] = Props, State) when (K =/= struct andalso
  150. K =/= array andalso
  151. K =/= json) ->
  152. json_encode_proplist(Props, State);
  153. json_encode({struct, Props}, State) when is_list(Props) ->
  154. json_encode_proplist(Props, State);
  155. json_encode({Props}, State) when is_list(Props) ->
  156. json_encode_proplist(Props, State);
  157. json_encode({}, State) ->
  158. json_encode_proplist([], State);
  159. json_encode(Array, State) when is_list(Array) ->
  160. json_encode_array(Array, State);
  161. json_encode({array, Array}, State) when is_list(Array) ->
  162. json_encode_array(Array, State);
  163. json_encode({json, IoList}, _State) ->
  164. IoList;
  165. json_encode(Bad, #encoder{handler=null}) ->
  166. exit({json_encode, {bad_term, Bad}});
  167. json_encode(Bad, State=#encoder{handler=Handler}) ->
  168. json_encode(Handler(Bad), State).
  169. json_encode_array([], _State) ->
  170. <<"[]">>;
  171. json_encode_array(L, State) ->
  172. F = fun (O, Acc) ->
  173. [$,, json_encode(O, State) | Acc]
  174. end,
  175. [$, | Acc1] = lists:foldl(F, "[", L),
  176. lists:reverse([$\] | Acc1]).
  177. json_encode_proplist([], _State) ->
  178. <<"{}">>;
  179. json_encode_proplist(Props, State) ->
  180. F = fun ({K, V}, Acc) ->
  181. KS = json_encode_string(K, State),
  182. VS = json_encode(V, State),
  183. [$,, VS, $:, KS | Acc]
  184. end,
  185. [$, | Acc1] = lists:foldl(F, "{", Props),
  186. lists:reverse([$\} | Acc1]).
  187. json_encode_string(A, State) when is_atom(A) ->
  188. L = atom_to_list(A),
  189. case json_string_is_safe(L) of
  190. true ->
  191. [?Q, L, ?Q];
  192. false ->
  193. json_encode_string_unicode(xmerl_ucs:from_utf8(L), State, [?Q])
  194. end;
  195. json_encode_string(B, State) when is_binary(B) ->
  196. case json_bin_is_safe(B) of
  197. true ->
  198. [?Q, B, ?Q];
  199. false ->
  200. json_encode_string_unicode(xmerl_ucs:from_utf8(B), State, [?Q])
  201. end;
  202. json_encode_string(I, _State) when is_integer(I) ->
  203. [?Q, integer_to_list(I), ?Q];
  204. json_encode_string(L, State) when is_list(L) ->
  205. case json_string_is_safe(L) of
  206. true ->
  207. [?Q, L, ?Q];
  208. false ->
  209. json_encode_string_unicode(L, State, [?Q])
  210. end.
  211. json_string_is_safe([]) ->
  212. true;
  213. json_string_is_safe([C | Rest]) ->
  214. case C of
  215. ?Q ->
  216. false;
  217. $\\ ->
  218. false;
  219. $\b ->
  220. false;
  221. $\f ->
  222. false;
  223. $\n ->
  224. false;
  225. $\r ->
  226. false;
  227. $\t ->
  228. false;
  229. C when C >= 0, C < $\s; C >= 16#7f, C =< 16#10FFFF ->
  230. false;
  231. C when C < 16#7f ->
  232. json_string_is_safe(Rest);
  233. _ ->
  234. false
  235. end.
  236. json_bin_is_safe(<<>>) ->
  237. true;
  238. json_bin_is_safe(<<C, Rest/binary>>) ->
  239. case C of
  240. ?Q ->
  241. false;
  242. $\\ ->
  243. false;
  244. $\b ->
  245. false;
  246. $\f ->
  247. false;
  248. $\n ->
  249. false;
  250. $\r ->
  251. false;
  252. $\t ->
  253. false;
  254. C when C >= 0, C < $\s; C >= 16#7f ->
  255. false;
  256. C when C < 16#7f ->
  257. json_bin_is_safe(Rest)
  258. end.
  259. json_encode_string_unicode([], _State, Acc) ->
  260. lists:reverse([$\" | Acc]);
  261. json_encode_string_unicode([C | Cs], State, Acc) ->
  262. Acc1 = case C of
  263. ?Q ->
  264. [?Q, $\\ | Acc];
  265. %% Escaping solidus is only useful when trying to protect
  266. %% against "</script>" injection attacks which are only
  267. %% possible when JSON is inserted into a HTML document
  268. %% in-line. mochijson2 does not protect you from this, so
  269. %% if you do insert directly into HTML then you need to
  270. %% uncomment the following case or escape the output of encode.
  271. %%
  272. %% $/ ->
  273. %% [$/, $\\ | Acc];
  274. %%
  275. $\\ ->
  276. [$\\, $\\ | Acc];
  277. $\b ->
  278. [$b, $\\ | Acc];
  279. $\f ->
  280. [$f, $\\ | Acc];
  281. $\n ->
  282. [$n, $\\ | Acc];
  283. $\r ->
  284. [$r, $\\ | Acc];
  285. $\t ->
  286. [$t, $\\ | Acc];
  287. C when C >= 0, C < $\s ->
  288. [unihex(C) | Acc];
  289. C when C >= 16#7f, C =< 16#10FFFF, State#encoder.utf8 ->
  290. [xmerl_ucs:to_utf8(C) | Acc];
  291. C when C >= 16#7f, C =< 16#10FFFF, not State#encoder.utf8 ->
  292. [unihex(C) | Acc];
  293. C when C < 16#7f ->
  294. [C | Acc];
  295. _ ->
  296. exit({json_encode, {bad_char, C}})
  297. end,
  298. json_encode_string_unicode(Cs, State, Acc1).
  299. hexdigit(C) when C >= 0, C =< 9 ->
  300. C + $0;
  301. hexdigit(C) when C =< 15 ->
  302. C + $a - 10.
  303. unihex(C) when C < 16#10000 ->
  304. <<D3:4, D2:4, D1:4, D0:4>> = <<C:16>>,
  305. Digits = [hexdigit(D) || D <- [D3, D2, D1, D0]],
  306. [$\\, $u | Digits];
  307. unihex(C) when C =< 16#10FFFF ->
  308. N = C - 16#10000,
  309. S1 = 16#d800 bor ((N bsr 10) band 16#3ff),
  310. S2 = 16#dc00 bor (N band 16#3ff),
  311. [unihex(S1), unihex(S2)].
  312. json_decode(L, S) when is_list(L) ->
  313. json_decode(iolist_to_binary(L), S);
  314. json_decode(B, S) ->
  315. {Res, S1} = decode1(B, S),
  316. {eof, _} = tokenize(B, S1#decoder{state=trim}),
  317. Res.
  318. decode1(B, S=#decoder{state=null}) ->
  319. case tokenize(B, S#decoder{state=any}) of
  320. {{const, C}, S1} ->
  321. {C, S1};
  322. {start_array, S1} ->
  323. decode_array(B, S1);
  324. {start_object, S1} ->
  325. decode_object(B, S1)
  326. end.
  327. make_object(V, #decoder{object_hook=N}) when N =:= null orelse N =:= struct ->
  328. V;
  329. make_object({struct, P}, #decoder{object_hook=eep18}) ->
  330. {P};
  331. make_object({struct, P}, #decoder{object_hook=proplist}) ->
  332. P;
  333. make_object(V, #decoder{object_hook=Hook}) ->
  334. Hook(V).
  335. decode_object(B, S) ->
  336. decode_object(B, S#decoder{state=key}, []).
  337. decode_object(B, S=#decoder{state=key}, Acc) ->
  338. case tokenize(B, S) of
  339. {end_object, S1} ->
  340. V = make_object({struct, lists:reverse(Acc)}, S1),
  341. {V, S1#decoder{state=null}};
  342. {{const, K}, S1} ->
  343. {colon, S2} = tokenize(B, S1),
  344. {V, S3} = decode1(B, S2#decoder{state=null}),
  345. decode_object(B, S3#decoder{state=comma}, [{K, V} | Acc])
  346. end;
  347. decode_object(B, S=#decoder{state=comma}, Acc) ->
  348. case tokenize(B, S) of
  349. {end_object, S1} ->
  350. V = make_object({struct, lists:reverse(Acc)}, S1),
  351. {V, S1#decoder{state=null}};
  352. {comma, S1} ->
  353. decode_object(B, S1#decoder{state=key}, Acc)
  354. end.
  355. decode_array(B, S) ->
  356. decode_array(B, S#decoder{state=any}, []).
  357. decode_array(B, S=#decoder{state=any}, Acc) ->
  358. case tokenize(B, S) of
  359. {end_array, S1} ->
  360. {lists:reverse(Acc), S1#decoder{state=null}};
  361. {start_array, S1} ->
  362. {Array, S2} = decode_array(B, S1),
  363. decode_array(B, S2#decoder{state=comma}, [Array | Acc]);
  364. {start_object, S1} ->
  365. {Array, S2} = decode_object(B, S1),
  366. decode_array(B, S2#decoder{state=comma}, [Array | Acc]);
  367. {{const, Const}, S1} ->
  368. decode_array(B, S1#decoder{state=comma}, [Const | Acc])
  369. end;
  370. decode_array(B, S=#decoder{state=comma}, Acc) ->
  371. case tokenize(B, S) of
  372. {end_array, S1} ->
  373. {lists:reverse(Acc), S1#decoder{state=null}};
  374. {comma, S1} ->
  375. decode_array(B, S1#decoder{state=any}, Acc)
  376. end.
  377. tokenize_string(B, S=#decoder{offset=O}) ->
  378. case tokenize_string_fast(B, O) of
  379. {escape, O1} ->
  380. Length = O1 - O,
  381. S1 = ?ADV_COL(S, Length),
  382. <<_:O/binary, Head:Length/binary, _/binary>> = B,
  383. tokenize_string(B, S1, lists:reverse(binary_to_list(Head)));
  384. O1 ->
  385. Length = O1 - O,
  386. <<_:O/binary, String:Length/binary, ?Q, _/binary>> = B,
  387. {{const, String}, ?ADV_COL(S, Length + 1)}
  388. end.
  389. tokenize_string_fast(B, O) ->
  390. case B of
  391. <<_:O/binary, ?Q, _/binary>> ->
  392. O;
  393. <<_:O/binary, $\\, _/binary>> ->
  394. {escape, O};
  395. <<_:O/binary, C1, _/binary>> when C1 < 128 ->
  396. tokenize_string_fast(B, 1 + O);
  397. <<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223,
  398. C2 >= 128, C2 =< 191 ->
  399. tokenize_string_fast(B, 2 + O);
  400. <<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239,
  401. C2 >= 128, C2 =< 191,
  402. C3 >= 128, C3 =< 191 ->
  403. tokenize_string_fast(B, 3 + O);
  404. <<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244,
  405. C2 >= 128, C2 =< 191,
  406. C3 >= 128, C3 =< 191,
  407. C4 >= 128, C4 =< 191 ->
  408. tokenize_string_fast(B, 4 + O);
  409. _ ->
  410. throw(invalid_utf8)
  411. end.
  412. tokenize_string(B, S=#decoder{offset=O}, Acc) ->
  413. case B of
  414. <<_:O/binary, ?Q, _/binary>> ->
  415. {{const, iolist_to_binary(lists:reverse(Acc))}, ?INC_COL(S)};
  416. <<_:O/binary, "\\\"", _/binary>> ->
  417. tokenize_string(B, ?ADV_COL(S, 2), [$\" | Acc]);
  418. <<_:O/binary, "\\\\", _/binary>> ->
  419. tokenize_string(B, ?ADV_COL(S, 2), [$\\ | Acc]);
  420. <<_:O/binary, "\\/", _/binary>> ->
  421. tokenize_string(B, ?ADV_COL(S, 2), [$/ | Acc]);
  422. <<_:O/binary, "\\b", _/binary>> ->
  423. tokenize_string(B, ?ADV_COL(S, 2), [$\b | Acc]);
  424. <<_:O/binary, "\\f", _/binary>> ->
  425. tokenize_string(B, ?ADV_COL(S, 2), [$\f | Acc]);
  426. <<_:O/binary, "\\n", _/binary>> ->
  427. tokenize_string(B, ?ADV_COL(S, 2), [$\n | Acc]);
  428. <<_:O/binary, "\\r", _/binary>> ->
  429. tokenize_string(B, ?ADV_COL(S, 2), [$\r | Acc]);
  430. <<_:O/binary, "\\t", _/binary>> ->
  431. tokenize_string(B, ?ADV_COL(S, 2), [$\t | Acc]);
  432. <<_:O/binary, "\\u", C3, C2, C1, C0, Rest/binary>> ->
  433. C = erlang:list_to_integer([C3, C2, C1, C0], 16),
  434. if C > 16#D7FF, C < 16#DC00 ->
  435. %% coalesce UTF-16 surrogate pair
  436. <<"\\u", D3, D2, D1, D0, _/binary>> = Rest,
  437. D = erlang:list_to_integer([D3,D2,D1,D0], 16),
  438. [CodePoint] = xmerl_ucs:from_utf16be(<<C:16/big-unsigned-integer,
  439. D:16/big-unsigned-integer>>),
  440. Acc1 = lists:reverse(xmerl_ucs:to_utf8(CodePoint), Acc),
  441. tokenize_string(B, ?ADV_COL(S, 12), Acc1);
  442. true ->
  443. Acc1 = lists:reverse(xmerl_ucs:to_utf8(C), Acc),
  444. tokenize_string(B, ?ADV_COL(S, 6), Acc1)
  445. end;
  446. <<_:O/binary, C1, _/binary>> when C1 < 128 ->
  447. tokenize_string(B, ?INC_CHAR(S, C1), [C1 | Acc]);
  448. <<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223,
  449. C2 >= 128, C2 =< 191 ->
  450. tokenize_string(B, ?ADV_COL(S, 2), [C2, C1 | Acc]);
  451. <<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239,
  452. C2 >= 128, C2 =< 191,
  453. C3 >= 128, C3 =< 191 ->
  454. tokenize_string(B, ?ADV_COL(S, 3), [C3, C2, C1 | Acc]);
  455. <<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244,
  456. C2 >= 128, C2 =< 191,
  457. C3 >= 128, C3 =< 191,
  458. C4 >= 128, C4 =< 191 ->
  459. tokenize_string(B, ?ADV_COL(S, 4), [C4, C3, C2, C1 | Acc]);
  460. _ ->
  461. throw(invalid_utf8)
  462. end.
  463. tokenize_number(B, S) ->
  464. case tokenize_number(B, sign, S, []) of
  465. {{int, Int}, S1} ->
  466. {{const, list_to_integer(Int)}, S1};
  467. {{float, Float}, S1} ->
  468. {{const, list_to_float(Float)}, S1}
  469. end.
  470. tokenize_number(B, sign, S=#decoder{offset=O}, []) ->
  471. case B of
  472. <<_:O/binary, $-, _/binary>> ->
  473. tokenize_number(B, int, ?INC_COL(S), [$-]);
  474. _ ->
  475. tokenize_number(B, int, S, [])
  476. end;
  477. tokenize_number(B, int, S=#decoder{offset=O}, Acc) ->
  478. case B of
  479. <<_:O/binary, $0, _/binary>> ->
  480. tokenize_number(B, frac, ?INC_COL(S), [$0 | Acc]);
  481. <<_:O/binary, C, _/binary>> when C >= $1 andalso C =< $9 ->
  482. tokenize_number(B, int1, ?INC_COL(S), [C | Acc])
  483. end;
  484. tokenize_number(B, int1, S=#decoder{offset=O}, Acc) ->
  485. case B of
  486. <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
  487. tokenize_number(B, int1, ?INC_COL(S), [C | Acc]);
  488. _ ->
  489. tokenize_number(B, frac, S, Acc)
  490. end;
  491. tokenize_number(B, frac, S=#decoder{offset=O}, Acc) ->
  492. case B of
  493. <<_:O/binary, $., C, _/binary>> when C >= $0, C =< $9 ->
  494. tokenize_number(B, frac1, ?ADV_COL(S, 2), [C, $. | Acc]);
  495. <<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E ->
  496. tokenize_number(B, esign, ?INC_COL(S), [$e, $0, $. | Acc]);
  497. _ ->
  498. {{int, lists:reverse(Acc)}, S}
  499. end;
  500. tokenize_number(B, frac1, S=#decoder{offset=O}, Acc) ->
  501. case B of
  502. <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
  503. tokenize_number(B, frac1, ?INC_COL(S), [C | Acc]);
  504. <<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E ->
  505. tokenize_number(B, esign, ?INC_COL(S), [$e | Acc]);
  506. _ ->
  507. {{float, lists:reverse(Acc)}, S}
  508. end;
  509. tokenize_number(B, esign, S=#decoder{offset=O}, Acc) ->
  510. case B of
  511. <<_:O/binary, C, _/binary>> when C =:= $- orelse C=:= $+ ->
  512. tokenize_number(B, eint, ?INC_COL(S), [C | Acc]);
  513. _ ->
  514. tokenize_number(B, eint, S, Acc)
  515. end;
  516. tokenize_number(B, eint, S=#decoder{offset=O}, Acc) ->
  517. case B of
  518. <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
  519. tokenize_number(B, eint1, ?INC_COL(S), [C | Acc])
  520. end;
  521. tokenize_number(B, eint1, S=#decoder{offset=O}, Acc) ->
  522. case B of
  523. <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
  524. tokenize_number(B, eint1, ?INC_COL(S), [C | Acc]);
  525. _ ->
  526. {{float, lists:reverse(Acc)}, S}
  527. end.
  528. tokenize(B, S=#decoder{offset=O}) ->
  529. case B of
  530. <<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
  531. tokenize(B, ?INC_CHAR(S, C));
  532. <<_:O/binary, "{", _/binary>> ->
  533. {start_object, ?INC_COL(S)};
  534. <<_:O/binary, "}", _/binary>> ->
  535. {end_object, ?INC_COL(S)};
  536. <<_:O/binary, "[", _/binary>> ->
  537. {start_array, ?INC_COL(S)};
  538. <<_:O/binary, "]", _/binary>> ->
  539. {end_array, ?INC_COL(S)};
  540. <<_:O/binary, ",", _/binary>> ->
  541. {comma, ?INC_COL(S)};
  542. <<_:O/binary, ":", _/binary>> ->
  543. {colon, ?INC_COL(S)};
  544. <<_:O/binary, "null", _/binary>> ->
  545. {{const, null}, ?ADV_COL(S, 4)};
  546. <<_:O/binary, "true", _/binary>> ->
  547. {{const, true}, ?ADV_COL(S, 4)};
  548. <<_:O/binary, "false", _/binary>> ->
  549. {{const, false}, ?ADV_COL(S, 5)};
  550. <<_:O/binary, "\"", _/binary>> ->
  551. tokenize_string(B, ?INC_COL(S));
  552. <<_:O/binary, C, _/binary>> when (C >= $0 andalso C =< $9)
  553. orelse C =:= $- ->
  554. tokenize_number(B, S);
  555. <<_:O/binary>> ->
  556. trim = S#decoder.state,
  557. {eof, S}
  558. end.
  559. %%
  560. %% Tests
  561. %%
  562. -ifdef(TEST).
  563. -include_lib("eunit/include/eunit.hrl").
  564. %% testing constructs borrowed from the Yaws JSON implementation.
  565. %% Create an object from a list of Key/Value pairs.
  566. obj_new() ->
  567. {struct, []}.
  568. is_obj({struct, Props}) ->
  569. F = fun ({K, _}) when is_binary(K) -> true end,
  570. lists:all(F, Props).
  571. obj_from_list(Props) ->
  572. Obj = {struct, Props},
  573. ?assert(is_obj(Obj)),
  574. Obj.
  575. %% Test for equivalence of Erlang terms.
  576. %% Due to arbitrary order of construction, equivalent objects might
  577. %% compare unequal as erlang terms, so we need to carefully recurse
  578. %% through aggregates (tuples and objects).
  579. equiv({struct, Props1}, {struct, Props2}) ->
  580. equiv_object(Props1, Props2);
  581. equiv(L1, L2) when is_list(L1), is_list(L2) ->
  582. equiv_list(L1, L2);
  583. equiv(N1, N2) when is_number(N1), is_number(N2) -> N1 == N2;
  584. equiv(B1, B2) when is_binary(B1), is_binary(B2) -> B1 == B2;
  585. equiv(A, A) when A =:= true orelse A =:= false orelse A =:= null -> true.
  586. %% Object representation and traversal order is unknown.
  587. %% Use the sledgehammer and sort property lists.
  588. equiv_object(Props1, Props2) ->
  589. L1 = lists:keysort(1, Props1),
  590. L2 = lists:keysort(1, Props2),
  591. Pairs = lists:zip(L1, L2),
  592. true = lists:all(fun({{K1, V1}, {K2, V2}}) ->
  593. equiv(K1, K2) and equiv(V1, V2)
  594. end, Pairs).
  595. %% Recursively compare tuple elements for equivalence.
  596. equiv_list([], []) ->
  597. true;
  598. equiv_list([V1 | L1], [V2 | L2]) ->
  599. equiv(V1, V2) andalso equiv_list(L1, L2).
  600. decode_test() ->
  601. [1199344435545.0, 1] = decode(<<"[1199344435545.0,1]">>),
  602. <<16#F0,16#9D,16#9C,16#95>> = decode([34,"\\ud835","\\udf15",34]).
  603. e2j_vec_test() ->
  604. test_one(e2j_test_vec(utf8), 1).
  605. test_one([], _N) ->
  606. %% io:format("~p tests passed~n", [N-1]),
  607. ok;
  608. test_one([{E, J} | Rest], N) ->
  609. %% io:format("[~p] ~p ~p~n", [N, E, J]),
  610. true = equiv(E, decode(J)),
  611. true = equiv(E, decode(encode(E))),
  612. test_one(Rest, 1+N).
  613. e2j_test_vec(utf8) ->
  614. [
  615. {1, "1"},
  616. {3.1416, "3.14160"}, %% text representation may truncate, trail zeroes
  617. {-1, "-1"},
  618. {-3.1416, "-3.14160"},
  619. {12.0e10, "1.20000e+11"},
  620. {1.234E+10, "1.23400e+10"},
  621. {-1.234E-10, "-1.23400e-10"},
  622. {10.0, "1.0e+01"},
  623. {123.456, "1.23456E+2"},
  624. {10.0, "1e1"},
  625. {<<"foo">>, "\"foo\""},
  626. {<<"foo", 5, "bar">>, "\"foo\\u0005bar\""},
  627. {<<"">>, "\"\""},
  628. {<<"\n\n\n">>, "\"\\n\\n\\n\""},
  629. {<<"\" \b\f\r\n\t\"">>, "\"\\\" \\b\\f\\r\\n\\t\\\"\""},
  630. {obj_new(), "{}"},
  631. {obj_from_list([{<<"foo">>, <<"bar">>}]), "{\"foo\":\"bar\"}"},
  632. {obj_from_list([{<<"foo">>, <<"bar">>}, {<<"baz">>, 123}]),
  633. "{\"foo\":\"bar\",\"baz\":123}"},
  634. {[], "[]"},
  635. {[[]], "[[]]"},
  636. {[1, <<"foo">>], "[1,\"foo\"]"},
  637. %% json array in a json object
  638. {obj_from_list([{<<"foo">>, [123]}]),
  639. "{\"foo\":[123]}"},
  640. %% json object in a json object
  641. {obj_from_list([{<<"foo">>, obj_from_list([{<<"bar">>, true}])}]),
  642. "{\"foo\":{\"bar\":true}}"},
  643. %% fold evaluation order
  644. {obj_from_list([{<<"foo">>, []},
  645. {<<"bar">>, obj_from_list([{<<"baz">>, true}])},
  646. {<<"alice">>, <<"bob">>}]),
  647. "{\"foo\":[],\"bar\":{\"baz\":true},\"alice\":\"bob\"}"},
  648. %% json object in a json array
  649. {[-123, <<"foo">>, obj_from_list([{<<"bar">>, []}]), null],
  650. "[-123,\"foo\",{\"bar\":[]},null]"}
  651. ].
  652. %% test utf8 encoding
  653. encoder_utf8_test() ->
  654. %% safe conversion case (default)
  655. [34,"\\u0001","\\u0442","\\u0435","\\u0441","\\u0442",34] =
  656. encode(<<1,"\321\202\320\265\321\201\321\202">>),
  657. %% raw utf8 output (optional)
  658. Enc = mochijson2:encoder([{utf8, true}]),
  659. [34,"\\u0001",[209,130],[208,181],[209,129],[209,130],34] =
  660. Enc(<<1,"\321\202\320\265\321\201\321\202">>).
  661. input_validation_test() ->
  662. Good = [
  663. {16#00A3, <<?Q, 16#C2, 16#A3, ?Q>>}, %% pound
  664. {16#20AC, <<?Q, 16#E2, 16#82, 16#AC, ?Q>>}, %% euro
  665. {16#10196, <<?Q, 16#F0, 16#90, 16#86, 16#96, ?Q>>} %% denarius
  666. ],
  667. lists:foreach(fun({CodePoint, UTF8}) ->
  668. Expect = list_to_binary(xmerl_ucs:to_utf8(CodePoint)),
  669. Expect = decode(UTF8)
  670. end, Good),
  671. Bad = [
  672. %% 2nd, 3rd, or 4th byte of a multi-byte sequence w/o leading byte
  673. <<?Q, 16#80, ?Q>>,
  674. %% missing continuations, last byte in each should be 80-BF
  675. <<?Q, 16#C2, 16#7F, ?Q>>,
  676. <<?Q, 16#E0, 16#80,16#7F, ?Q>>,
  677. <<?Q, 16#F0, 16#80, 16#80, 16#7F, ?Q>>,
  678. %% we don't support code points > 10FFFF per RFC 3629
  679. <<?Q, 16#F5, 16#80, 16#80, 16#80, ?Q>>,
  680. %% escape characters trigger a different code path
  681. <<?Q, $\\, $\n, 16#80, ?Q>>
  682. ],
  683. lists:foreach(
  684. fun(X) ->
  685. ok = try decode(X) catch invalid_utf8 -> ok end,
  686. %% could be {ucs,{bad_utf8_character_code}} or
  687. %% {json_encode,{bad_char,_}}
  688. {'EXIT', _} = (catch encode(X))
  689. end, Bad).
  690. inline_json_test() ->
  691. ?assertEqual(<<"\"iodata iodata\"">>,
  692. iolist_to_binary(
  693. encode({json, [<<"\"iodata">>, " iodata\""]}))),
  694. ?assertEqual({struct, [{<<"key">>, <<"iodata iodata">>}]},
  695. decode(
  696. encode({struct,
  697. [{key, {json, [<<"\"iodata">>, " iodata\""]}}]}))),
  698. ok.
  699. big_unicode_test() ->
  700. UTF8Seq = list_to_binary(xmerl_ucs:to_utf8(16#0001d120)),
  701. ?assertEqual(
  702. <<"\"\\ud834\\udd20\"">>,
  703. iolist_to_binary(encode(UTF8Seq))),
  704. ?assertEqual(
  705. UTF8Seq,
  706. decode(iolist_to_binary(encode(UTF8Seq)))),
  707. ok.
  708. custom_decoder_test() ->
  709. ?assertEqual(
  710. {struct, [{<<"key">>, <<"value">>}]},
  711. (decoder([]))("{\"key\": \"value\"}")),
  712. F = fun ({struct, [{<<"key">>, <<"value">>}]}) -> win end,
  713. ?assertEqual(
  714. win,
  715. (decoder([{object_hook, F}]))("{\"key\": \"value\"}")),
  716. ok.
  717. atom_test() ->
  718. %% JSON native atoms
  719. [begin
  720. ?assertEqual(A, decode(atom_to_list(A))),
  721. ?assertEqual(iolist_to_binary(atom_to_list(A)),
  722. iolist_to_binary(encode(A)))
  723. end || A <- [true, false, null]],
  724. %% Atom to string
  725. ?assertEqual(
  726. <<"\"foo\"">>,
  727. iolist_to_binary(encode(foo))),
  728. ?assertEqual(
  729. <<"\"\\ud834\\udd20\"">>,
  730. iolist_to_binary(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))),
  731. ok.
  732. key_encode_test() ->
  733. %% Some forms are accepted as keys that would not be strings in other
  734. %% cases
  735. ?assertEqual(
  736. <<"{\"foo\":1}">>,
  737. iolist_to_binary(encode({struct, [{foo, 1}]}))),
  738. ?assertEqual(
  739. <<"{\"foo\":1}">>,
  740. iolist_to_binary(encode({struct, [{<<"foo">>, 1}]}))),
  741. ?assertEqual(
  742. <<"{\"foo\":1}">>,
  743. iolist_to_binary(encode({struct, [{"foo", 1}]}))),
  744. ?assertEqual(
  745. <<"{\"foo\":1}">>,
  746. iolist_to_binary(encode([{foo, 1}]))),
  747. ?assertEqual(
  748. <<"{\"foo\":1}">>,
  749. iolist_to_binary(encode([{<<"foo">>, 1}]))),
  750. ?assertEqual(
  751. <<"{\"foo\":1}">>,
  752. iolist_to_binary(encode([{"foo", 1}]))),
  753. ?assertEqual(
  754. <<"{\"\\ud834\\udd20\":1}">>,
  755. iolist_to_binary(
  756. encode({struct, [{[16#0001d120], 1}]}))),
  757. ?assertEqual(
  758. <<"{\"1\":1}">>,
  759. iolist_to_binary(encode({struct, [{1, 1}]}))),
  760. ok.
  761. unsafe_chars_test() ->
  762. Chars = "\"\\\b\f\n\r\t",
  763. [begin
  764. ?assertEqual(false, json_string_is_safe([C])),
  765. ?assertEqual(false, json_bin_is_safe(<<C>>)),
  766. ?assertEqual(<<C>>, decode(encode(<<C>>)))
  767. end || C <- Chars],
  768. ?assertEqual(
  769. false,
  770. json_string_is_safe([16#0001d120])),
  771. ?assertEqual(
  772. false,
  773. json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8(16#0001d120)))),
  774. ?assertEqual(
  775. [16#0001d120],
  776. xmerl_ucs:from_utf8(
  777. binary_to_list(
  778. decode(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))))),
  779. ?assertEqual(
  780. false,
  781. json_string_is_safe([16#110000])),
  782. ?assertEqual(
  783. false,
  784. json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8([16#110000])))),
  785. %% solidus can be escaped but isn't unsafe by default
  786. ?assertEqual(
  787. <<"/">>,
  788. decode(<<"\"\\/\"">>)),
  789. ok.
  790. int_test() ->
  791. ?assertEqual(0, decode("0")),
  792. ?assertEqual(1, decode("1")),
  793. ?assertEqual(11, decode("11")),
  794. ok.
  795. large_int_test() ->
  796. ?assertEqual(<<"-2147483649214748364921474836492147483649">>,
  797. iolist_to_binary(encode(-2147483649214748364921474836492147483649))),
  798. ?assertEqual(<<"2147483649214748364921474836492147483649">>,
  799. iolist_to_binary(encode(2147483649214748364921474836492147483649))),
  800. ok.
  801. float_test() ->
  802. ?assertEqual(<<"-2147483649.0">>, iolist_to_binary(encode(-2147483649.0))),
  803. ?assertEqual(<<"2147483648.0">>, iolist_to_binary(encode(2147483648.0))),
  804. ok.
  805. handler_test() ->
  806. ?assertEqual(
  807. {'EXIT',{json_encode,{bad_term,{x,y}}}},
  808. catch encode({x,y})),
  809. F = fun ({x,y}) -> [] end,
  810. ?assertEqual(
  811. <<"[]">>,
  812. iolist_to_binary((encoder([{handler, F}]))({x, y}))),
  813. ok.
  814. encode_empty_test_() ->
  815. [{A, ?_assertEqual(<<"{}">>, iolist_to_binary(encode(B)))}
  816. || {A, B} <- [{"eep18 {}", {}},
  817. {"eep18 {[]}", {[]}},
  818. {"{struct, []}", {struct, []}}]].
  819. encode_test_() ->
  820. P = [{<<"k">>, <<"v">>}],
  821. JSON = iolist_to_binary(encode({struct, P})),
  822. [{atom_to_list(F),
  823. ?_assertEqual(JSON, iolist_to_binary(encode(decode(JSON, [{format, F}]))))}
  824. || F <- [struct, eep18, proplist]].
  825. format_test_() ->
  826. P = [{<<"k">>, <<"v">>}],
  827. JSON = iolist_to_binary(encode({struct, P})),
  828. [{atom_to_list(F),
  829. ?_assertEqual(A, decode(JSON, [{format, F}]))}
  830. || {F, A} <- [{struct, {struct, P}},
  831. {eep18, {P}},
  832. {proplist, P}]].
  833. -endif.