%% The MIT License %% Copyright (c) 2010-2013 Alisdair Sullivan %% Permission is hereby granted, free of charge, to any person obtaining a copy %% of this software and associated documentation files (the "Software"), to deal %% in the Software without restriction, including without limitation the rights %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell %% copies of the Software, and to permit persons to whom the Software is %% furnished to do so, subject to the following conditions: %% The above copyright notice and this permission notice shall be included in %% all copies or substantial portions of the Software. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN %% THE SOFTWARE. -module(jsx_to_term). -export([to_term/2]). -export([init/1, handle_event/2]). -export([start_object/1, start_array/1, finish/1, insert/2, insert/3]). -record(config, { labels = binary }). -type config() :: list(). -type json_value() :: list({binary(), json_value()}) | list(json_value()) | true | false | null | integer() | float() | binary(). -spec to_term(Source::binary(), Config::config()) -> json_value(). to_term(Source, Config) when is_list(Config) -> (jsx:decoder(?MODULE, Config, jsx_config:extract_config(Config)))(Source). parse_config(Config) -> parse_config(Config, #config{}). parse_config([{labels, Val}|Rest], Config) when Val == binary; Val == atom; Val == existing_atom; Val == attempt_atom -> parse_config(Rest, Config#config{labels = Val}); parse_config([labels|Rest], Config) -> parse_config(Rest, Config#config{labels = binary}); parse_config([{K, _}|Rest] = Options, Config) -> case lists:member(K, jsx_config:valid_flags()) of true -> parse_config(Rest, Config) ; false -> erlang:error(badarg, [Options, Config]) end; parse_config([K|Rest] = Options, Config) -> case lists:member(K, jsx_config:valid_flags()) of true -> parse_config(Rest, Config) ; false -> erlang:error(badarg, [Options, Config]) end; parse_config([], Config) -> Config. init(Config) -> {[], parse_config(Config)}. handle_event(end_json, {Term, _Config}) -> Term; handle_event(start_object, {Stack, Config}) -> {start_object(Stack), Config}; handle_event(end_object, {Stack, Config}) -> {finish(Stack), Config}; handle_event(start_array, {Stack, Config}) -> {start_array(Stack), Config}; handle_event(end_array, {Stack, Config}) -> {finish(Stack), Config}; handle_event({key, Key}, {Stack, Config}) -> {insert(format_key(Key, Config), Stack), Config}; handle_event({_, Event}, {Stack, Config}) -> {insert(Event, Stack), Config}. format_key(Key, Config) -> case Config#config.labels of binary -> Key ; atom -> binary_to_atom(Key, utf8) ; existing_atom -> binary_to_existing_atom(Key, utf8) ; attempt_atom -> try binary_to_existing_atom(Key, utf8) of Result -> Result catch error:badarg -> Key end end. %% internal state is a stack of in progress objects/arrays %% `[Current, Parent, Grandparent,...OriginalAncestor]` %% an object has the representation on the stack of %% `{object, [{NthKey, NthValue}, {NMinus1Key, NthMinus1Value},...{FirstKey, FirstValue}]}` %% of if there's a key with a yet to be matched value %% `{object, Key, [{NthKey, NthValue},...]}` %% an array looks like %% `{array, [NthValue, NthMinus1Value,...FirstValue]}` %% allocate a new object on top of the stack start_object(Stack) -> [{object, []}] ++ Stack. %% allocate a new array on top of the stack start_array(Stack) -> [{array, []}] ++ Stack. %% finish an object or array and insert it into the parent object if it exists finish([{object, []}]) -> [{}]; finish([{object, []}|Rest]) -> insert([{}], Rest); finish([{object, Pairs}]) -> lists:reverse(Pairs); finish([{object, Pairs}|Rest]) -> insert(lists:reverse(Pairs), Rest); finish([{array, Values}]) -> lists:reverse(Values); finish([{array, Values}|Rest]) -> insert(lists:reverse(Values), Rest); finish(_) -> erlang:error(badarg). %% insert a value when there's no parent object or array insert(Value, []) -> Value; %% insert a key or value into an object or array, autodetects the 'right' thing insert(Key, [{object, Pairs}|Rest]) -> [{object, Key, Pairs}] ++ Rest; insert(Value, [{object, Key, Pairs}|Rest]) -> [{object, [{Key, Value}] ++ Pairs}] ++ Rest; insert(Value, [{array, Values}|Rest]) -> [{array, [Value] ++ Values}] ++ Rest; insert(_, _) -> erlang:error(badarg). %% insert a key/value pair into an object insert(Key, Value, [{object, Pairs}|Rest]) -> [{object, [{Key, Value}] ++ Pairs}] ++ Rest; insert(_, _, _) -> erlang:error(badarg). %% eunit tests -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). config_test_() -> [ {"empty config", ?_assertEqual(#config{}, parse_config([]))}, {"implicit binary labels", ?_assertEqual(#config{}, parse_config([labels]))}, {"binary labels", ?_assertEqual(#config{}, parse_config([{labels, binary}]))}, {"atom labels", ?_assertEqual(#config{labels=atom}, parse_config([{labels, atom}]))}, {"existing atom labels", ?_assertEqual( #config{labels=existing_atom}, parse_config([{labels, existing_atom}]) )}, {"invalid opt flag", ?_assertError(badarg, parse_config([error]))}, {"invalid opt tuple", ?_assertError(badarg, parse_config([{error, true}]))} ]. format_key_test_() -> [ {"binary key", ?_assertEqual(<<"key">>, format_key(<<"key">>, #config{labels=binary}))}, {"atom key", ?_assertEqual(key, format_key(<<"key">>, #config{labels=atom}))}, {"existing atom key", ?_assertEqual( key, format_key(<<"key">>, #config{labels=existing_atom}) )}, {"nonexisting atom key", ?_assertError( badarg, format_key(<<"nonexistentatom">>, #config{labels=existing_atom}) )}, {"sloppy existing atom key", ?_assertEqual( key, format_key(<<"key">>, #config{labels=attempt_atom}) )}, {"nonexisting atom key", ?_assertEqual( <<"nonexistentatom">>, format_key(<<"nonexistentatom">>, #config{labels=attempt_atom}) )} ]. rep_manipulation_test_() -> [ {"allocate a new object on an empty stack", ?_assertEqual( [{object, []}], start_object([]) )}, {"allocate a new object on a stack", ?_assertEqual( [{object, []}, {object, []}], start_object([{object, []}]) )}, {"allocate a new array on an empty stack", ?_assertEqual( [{array, []}], start_array([]) )}, {"allocate a new array on a stack", ?_assertEqual( [{array, []}, {object, []}], start_array([{object, []}]) )}, {"insert a key into an object", ?_assertEqual( [{object, key, []}, junk], insert(key, [{object, []}, junk]) )}, {"insert a value into an object", ?_assertEqual( [{object, [{key, value}]}, junk], insert(value, [{object, key, []}, junk]) )}, {"insert a value into an array", ?_assertEqual( [{array, [value]}, junk], insert(value, [{array, []}, junk]) )}, {"insert a key/value pair into an object", ?_assertEqual( [{object, [{key, value}, {x, y}]}, junk], insert(key, value, [{object, [{x, y}]}, junk]) )}, {"finish an object with no ancestor", ?_assertEqual( [{a, b}, {x, y}], finish([{object, [{x, y}, {a, b}]}]) )}, {"finish an empty object", ?_assertEqual( [{}], finish([{object, []}]) )}, {"finish an object with an ancestor", ?_assertEqual( [{object, [{key, [{a, b}, {x, y}]}, {foo, bar}]}], finish([{object, [{x, y}, {a, b}]}, {object, key, [{foo, bar}]}]) )}, {"finish an array with no ancestor", ?_assertEqual( [a, b, c], finish([{array, [c, b, a]}]) )}, {"finish an array with an ancestor", ?_assertEqual( [{array, [[a, b, c], d, e, f]}], finish([{array, [c, b, a]}, {array, [d, e, f]}]) )} ]. handle_event_test_() -> Data = jsx:test_cases(), [ { Title, ?_assertEqual( Term, lists:foldl(fun handle_event/2, init([]), Events ++ [end_json]) ) } || {Title, _, Term, Events} <- Data ]. -endif.