From 79b8740da82edeb1dd431c927889382c16f4a43c Mon Sep 17 00:00:00 2001 From: alisdair sullivan Date: Fri, 6 Apr 2012 09:05:08 -0700 Subject: [PATCH] post_decode working --- src/jsx_to_term.erl | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/jsx_to_term.erl b/src/jsx_to_term.erl index 8bdcdba..d124cc1 100644 --- a/src/jsx_to_term.erl +++ b/src/jsx_to_term.erl @@ -185,5 +185,46 @@ naked_test_() -> {"naked literal", ?_assertEqual(to_term(<<"true">>, []), true)}, {"naked string", ?_assertEqual(to_term(<<"\"string\"">>, []), <<"string">>)} ]. + +post_decoders_test_() -> + JSON = <<"{\"object\": { + \"literals\": [true, false, null], + \"strings\": [\"foo\", \"bar\", \"baz\"], + \"numbers\": [1, 1.0, 1e0] + }}">>, + [ + {"no post_decode", ?_assertEqual( + to_term(JSON, []), + [{<<"object">>, [ + {<<"literals">>, [true, false, null]}, + {<<"strings">>, [<<"foo">>, <<"bar">>, <<"baz">>]}, + {<<"numbers">>, [1, 1.0, 1.0]} + ]}] + )}, + {"replace arrays with empty arrays", ?_assertEqual( + to_term(JSON, [{post_decode, fun([T|_] = V) when is_tuple(T) -> V; (V) when is_list(V) -> []; (V) -> V end}]), + [{<<"object">>, [{<<"literals">>, []}, {<<"strings">>, []}, {<<"numbers">>, []}]}] + )}, + {"replace objects with empty objects", ?_assertEqual( + to_term(JSON, [{post_decode, fun(V) when is_list(V) -> [{}]; (V) -> V end}]), + [{}] + )}, + {"replace all non-list values with false", ?_assertEqual( + to_term(JSON, [{post_decode, fun(V) when is_list(V) -> V; (_) -> false end}]), + [{<<"object">>, [ + {<<"literals">>, [false, false, false]}, + {<<"strings">>, [false, false, false]}, + {<<"numbers">>, [false, false, false]} + ]}] + )}, + {"atoms_to_strings", ?_assertEqual( + to_term(JSON, [{post_decode, fun(V) when is_atom(V) -> unicode:characters_to_binary(atom_to_list(V)); (V) -> V end}]), + [{<<"object">>, [ + {<<"literals">>, [<<"true">>, <<"false">>, <<"null">>]}, + {<<"strings">>, [<<"foo">>, <<"bar">>, <<"baz">>]}, + {<<"numbers">>, [1, 1.0, 1.0]} + ]}] + )} + ]. -endif.